我想在 Python 3.4 中使用 urllib 登录网站
import urllib.parse
import urllib.request
import http.cookiejar
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener)
url = 'http://mysite.org'
values = {"username" : "MyUsername123",
"password" : "MyPass123"}
data = urllib.parse.urlencode(values)
binary_data = data.encode('utf8')
req = urllib.request.Request(url, binary_data)
response = urllib.request.urlopen(req).read().decode("utf8", 'ignore')
print(response)
当我运行它时,输出是登录页面,而不是登录后的页面。在 Python 2.7 中,我使用 mechanize 完成了它,现在我不能,因为它与 3.4 不兼容。