如何使用urllib,urllib2和ClientCookie通过Python脚本登录phpBB3论坛?
时间:2020-03-06 14:31:12 来源:igfitidea点击:
(ClientCookie是用于(自动)cookie处理的模块:http://wwwsearch.sourceforge.net/ClientCookie)
# I encode the data I'll be sending: data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'}) # And I send it and read the page: page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data) output = page.read()
该脚本未登录,但似乎被重定向回同一登录页面,要求其提供用户名和密码。我究竟做错了什么?
任何帮助将不胜感激!谢谢!
解决方案
我们是否尝试过先获取登录页面?
我建议我们使用篡改数据来窥视当我们请求登录页面时发送的内容,然后从头开始使用Web浏览器从头开始正常登录,而没有初始cookie,以便脚本可以准确地复制它。 。
这是我在编写以下内容时使用的方法,该方法是从需要登录到Invision Power Board论坛的脚本中提取的,使用cookielib和urllib2可能会有用,可以作为参考。
import cookielib import logging import sys import urllib import urllib2 cookies = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies)) urllib2.install_opener(opener) headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12', 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language': 'en-gb,en;q=0.5', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', } # Fetch the login page to set initial cookies urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers)) # Login so we can access the Off Topic forum login_headers = headers.copy() login_headers.update({ 'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00', 'Content-Type': 'application/x-www-form-urlencoded', }) html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01', urllib.urlencode({ 'referer': 'http://www.rllmukforum.com/index.php?', 'UserName': RLLMUK_USERNAME, 'PassWord': RLLMUK_PASSWORD, }), login_headers)).read() if 'The following errors were found' in html: logging.error('RLLMUK login failed') logging.info(html) sys.exit(1)
我建议看一下机械化库。专为此类任务而设计。这比手工操作要容易得多。