首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用urllib,urllib2和ClientCookie通过Python脚本登录phpBB3论坛?

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

Stack Overflow用户
提问于 2018-09-06 05:04:23
回答 2查看 0关注 0票数 0

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

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

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

EN

回答 2

Stack Overflow用户

发布于 2018-09-06 13:34:27

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

我建议使用篡改数据来查看当您请求登录页面时发送的内容,然后使用网络浏览器从一开始就正常登录,没有初始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)
票数 0
EN

Stack Overflow用户

发布于 2018-09-06 14:31:15

我建议你看看mechanize库;它正是为这种类型的任务而设计的。这也比手工做容易得多。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100000732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档