抓取一个需要他们给你一个会话cookie firs的网页

2024-05-14 21:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从一个政府的“召集名单”数据库中搜集一份excel文件。但是,我必须访问此excel文件的URL:

http://nrega.ap.gov.in/Nregs/FrontServlet?requestType=HouseholdInf_engRH&hhid=192420317026010002&actionVal=musterrolls&type=Normal

要求我将来自政府网站的会话cookie附加到请求。

我如何获取会话cookie和对登录页的初始请求(当他们给您会话cookie时),然后使用它点击上面的URL来获取我们的excel文件?我在使用Python的Google应用程序引擎上。

我试过这个:

import urllib2
import cookielib

url = 'http://nrega.ap.gov.in/Nregs/FrontServlet?requestType=HouseholdInf_engRH&hhid=192420317026010002&actionVal=musterrolls&type=Normal'


def grab_data_with_cookie(cookie_jar, url):
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
    data = opener.open(url)
    return data

cj = cookielib.CookieJar()

#grab the data 
data1 = grab_data_with_cookie(cj, url)
#the second time we do this, we get back the excel sheet.
data2 = grab_data_with_cookie(cj, url)

stuff2  = data2.read()

我敢肯定这不是最好的办法。我怎样才能做得更干净,甚至使用请求库?


Tags: 文件thehttpurldatacookiewithopener
2条回答

使用requests这是一项微不足道的任务:

>>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'
>>> r = requests.get(url)

>>> print r.cookies
{'requests-is': 'awesome'}

使用cookies和urllib2

import cookielib
import urllib2

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# use opener to open different urls

可以将同一个打开器用于多个连接:

data = [opener.open(url).read() for url in urls]

或在全球安装:

urllib2.install_opener(opener)

在后一种情况下,无论是否支持cookies,其余代码看起来都一样:

data = [urllib2.urlopen(url).read() for url in urls]

相关问题 更多 >

    热门问题