如何使用urllib登录网站?

尼克·克莱恩(Niek de Klein)

我正在尝试登录此网站:http : //www.broadinstitute.org/cmap/index.jsp我在Windows上使用python 3.3。我遵循了这个答案https://stackoverflow.com/a/2910487/651779我的代码:

import http.cookiejar
import urllib

url = 'http://www.broadinstitute.org/cmap/index.jsp'
values = {'j_username' : 'username',
          'j_password' : 'password'}

data = urllib.parse.urlencode(values)
binary_data = data.encode('ascii')
cookies = http.cookiejar.CookieJar()

opener = urllib.request.build_opener(
    urllib.request.HTTPRedirectHandler(),
    urllib.request.HTTPHandler(debuglevel=0),
    urllib.request.HTTPSHandler(debuglevel=0),
    urllib.request.HTTPCookieProcessor(cookies))

response = opener.open(url, binary_data)
the_page = response.read()
http_headers = response.info()

它运行时没有错误,但是htmlthe_page只是登录页面。如何登录该页面?

用户名

由于HTTP请求是无状态的,因此该站点正在使用JSESSIONID cookie创建会话。发出请求时,不会先获取该会话ID。

我使用Fiddler嗅探了一个会话以登录该站点,发现POST是针对另一个URL进行的,但是它设置了JSESSIONID cookie。因此,您需要先获取URL,使用cookiehandler捕获该cookie,然后发布到该URL:

post_url = 'http://www.broadinstitute.org/cmap/j_security_check'

您根本不需要保存HTTP GET请求,只需调用opener.open(url),然后在代码中将响应行更改为此:

response = opener.open(post_url, binary_data)

此外,有效负载缺少提交方法。这是我建议的更改的全部内容:

import http.cookiejar
import urllib

get_url = 'http://www.broadinstitute.org/cmap/index.jsp'
post_url = 'http://www.broadinstitute.org/cmap/j_security_check'

values = urllib.parse.urlencode({'j_username': <MYCOOLUSERNAME>,
          'j_password': <MYCOOLPASSSWORD>,
          'submit': 'sign in'})
payload = bytes(values, 'ascii')
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
    urllib.request.HTTPRedirectHandler(),
    urllib.request.HTTPHandler(debuglevel=0),
    urllib.request.HTTPSHandler(debuglevel=0),
    urllib.request.HTTPCookieProcessor(cj))

opener.open(get_url) #First call to capture the JSESSIONID
resp = opener.open(post_url, payload)
resp_html = resp.read()
resp_headers = resp.info()

使用您创建的打开程序的任何其他请求都将重复使用该cookie,您应该能够自由浏览该站点。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章