Python - 认证后读取网页
首先,抱歉我的英语不是很好,可能有些语法错误,但这应该不会要了你的命 :) 希望如此。
我在一个网页上获取信息时遇到了麻烦,因为它有一个认证系统。
这个网站是:www.matchendirect.fr,这是一个法国网站,无法切换成英文(抱歉给你带来不便)。这个网站显示的是足球比赛的信息。
我的目的是获取预测数据(在页面中间有一个表格,显示了“Pronostics des internautes”,但这个表格的内容只有在你登录后才能看到)。
这是我的代码:
import urllib2, cookielib
cookieJar = cookielib.CookieJar()
auth_url="http://www.matchendirect.fr/cgi/ajax/authentification.php?f_contexte=auth_form_action&f_email=pkwpa&f_mot_de_passe=pkw_pa"
url="http://www.matchendirect.fr/live-score/colombie-bresil.html"
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
request = urllib2.Request(auth_url)
response = opener.open(request)
response = opener.open(url)
webpage=response.read()
为了确保我们已经登录,我们可以尝试这个:
if webpage.find("prono_stat_data")!=-1:
print("I'm logged in")
我觉得我的cookie管理得不好……
这是我的登录信息,可以随便用一下,这显然是一个为了这个话题而创建的假账号。
用户名:pkwpa
密码:pkw_pa
希望有人能帮我。
2 个回答
0
试着在打开的地方加个头部。我之前也遇到过类似的问题,通过加这个头部解决了。
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')
就是把它加到代码里。
import urllib2, cookielib
cookieJar = cookielib.CookieJar()
auth_url="http://www.matchendirect.fr/cgi/ajax/authentification.php? f_contexte=auth_form_action&f_email=pkwpa&f_mot_de_passe=pkw_pa"
url="http://www.matchendirect.fr/live-score/colombie-bresil.html"
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
request = urllib2.Request(auth_url)
response = opener.open(request)
response = opener.open(url)
webpage=response.read()
0
这里是你需要的内容:http://docs.python-requests.org/en/latest/user/install/#install。你可以这样使用它:
with session() as c:
c.get('http://www.matchendirect.fr/cgi/ajax/authentification.php?f_contexte=auth_form_action&f_email=pkwpa&f_mot_de_passe=pkw_pa')
request = c.get('http://www.matchendirect.fr/live-score/colombie-bresil.html')
print request.headers
print request.text
祝好!