如何使用urllib,urllib2和ClientCookie通过Python脚本登录phpBB3论坛?

StackOverflow https://stackoverflow.com/questions/112768

  •  02-07-2019
  •  | 
  •  

(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()

脚本没有登录,而是似乎被重定向回相同的登录页面,要求输入用户名和密码。我做错了什么?

任何帮助将不胜感激!谢谢!

有帮助吗?

解决方案

您是否尝试过首先获取登录页面?

我建议您使用篡改数据来查看确切地说,当你请求登录页面时发送的是什么,然后从一个新的开始使用网络浏览器正常登录,没有初始cookie,这样你的脚本就可以完全复制它。

这是我在编写以下内容时使用的方法,从需要使用cookielib和urllib2登录Invision Power Board论坛的脚本中提取 - 您可能会发现它可用作参考。

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)

其他提示

我建议您查看 mechanize 库;它专为此类任务而设计。它也比手工操作容易得多。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top