python请求无法下载zip文件,而浏览器/硒可以

时间:2018-06-22 04:43:54

标签: python web-scraping python-requests

我尝试使用请求模块通过以下代码下载一堆zip文件:

s = requests.Session()
url='http://data.theice.com/MyAccount/Login.aspx'
z=s.get(url)
soup=BeautifulSoup(z.content,'html.parser')
hidden=soup.find_all('input',attrs={'type':'hidden'})
values={'ctl00$ContentPlaceHolder1$LoginControl$m_userName':'Acorn437',
    'ctl00$ContentPlaceHolder1$LoginControl$m_password':'*******',
    '__EVENTTARGET':'ctl00$ContentPlaceHolder1$LoginControl$LoginButton',
    '__EVENTARGUMENT':'',
    '__LASTFOCUS':''}
values=dict(values,**{i['id']:i['value'] for i in hidden})
z=s.post(url,data=values,allow_redirects=True)

在此之后,我通过检查响应来验证我已成功登录该网站。现在,我想从网站上的链接下载zip文件

link='http://data.theice.com/MyAccount/Download.aspx?PUID=69590&PDS=0&PRODID=580&TS=2018'
resp=s.get(link,allow_redirects=True)   
path=os.getcwd()+'\\data\\ice_zip\\'
fname='test.zip'
zfile=open(path+fname,'wb')
zfile.write(resp.content)
zfile.close()

但是,事实证明,我下载的内容实际上是我需要的zip文件的html文件。我不知道为什么请求模块不适用于该网站。我认为在使用request.session登录后,我应该可以下载它,因为我可以使用浏览器或selenium模块来进行操作。

很显然,我登录

没问题

1 个答案:

答案 0 :(得分:1)

这对我有用-当然,您可以提供自己的凭据和下载路径...我认为您的主要问题可能是您的登录URL错误。当我运行您的代码时,我无法登录该站点。初始URL和登录URL是不同的。

import requests
from bs4 import BeautifulSoup

# define variables
username = ""
password = ""
path_to_store_output = ""

session = requests.Session()
r = session.get('http://data.theice.com/MyAccount/Login.aspx'')
soup=BeautifulSoup(r.text,'html.parser')

vs_generator = soup.find('input', attrs={'id': '__VIEWSTATEGENERATOR'}).get('value')
vs = soup.find('input', attrs={'id': '__VIEWSTATE'}).get('value')
event_validation = soup.find('input', attrs={'id': '__EVENTVALIDATION'}).get('value')


payload = {
    "__EVENTTARGET": "ctl00$ContentPlaceHolder1$LoginControl$LoginButton",
    "__EVENTARGUMENT":"", 
    "__LASTFOCUS": "", 
    "__VIEWSTATE": vs,
    "__VIEWSTATEGENERATOR": vs_generator,
    "__EVENTVALIDATION": event_validation,
    "ctl00$ContentPlaceHolder1$LoginControl$m_userName": username,
    "ctl00$ContentPlaceHolder1$LoginControl$m_password": password  
}
# doing a POST to login
r = session.post("http://www.ice.if5.com/MyAccount/Login.aspx", data=payload, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'})

# check if we're logged in
if not username in r.text:
    print("[!] Bommer, dude! We're not logged in...")

else:
    print("[*] Score, we're in. Let's download stuff...")
    r = session.get("http://www.ice.if5.com/MyAccount/Download.aspx?PUID=70116&PDS=2&PRODID=4133", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'})
    with open(path_to_store_output, 'wb') as f:
        f.write(r.content)

实际上并没有太多。登录并获取内容。替换该网址,用您感兴趣的内容进行测试。您提供的网址给了我404。加油。