抓一个网页,要求他们先给你一个会话cookie

rd1*_*108 5 python google-app-engine urllib2 web-scraping

我正试图从政府的"集合卷"数据库中抓取一个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 App Engine上.

我试过这个:

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()
Run Code Online (Sandbox Code Playgroud)

我很确定这不是最好的方法.我怎么能更干净地,甚至使用请求库?

Bur*_*lid 11

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

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

>>> print r.cookies
{'requests-is': 'awesome'}
Run Code Online (Sandbox Code Playgroud)