我正试图从政府的“集合卷”数据库中删除一个excel文件。但是,我必须访问此Excel文件的URL:
要求我有一个来自政府网站的会话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()
我很确定这不是最好的方法。我怎么能更干净地,甚至使用请求库?
答案 0 :(得分:11)
使用requests这是一项微不足道的任务:
>>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'
>>> r = requests.get(url)
>>> print r.cookies
{'requests-is': 'awesome'}
答案 1 :(得分:3)
使用Cookie和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)
在后一种情况下,无论是否支持cookie,其余代码看起来都是一样的:
data = [urllib2.urlopen(url).read() for url in urls]