[英]python requests cannot download a zip file while browser/selenium can
我嘗試使用請求模塊通過以下代碼下載一堆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模塊來進行操作。
顯然,我沒有問題登錄
這對我有用-當然,您可以提供自己的憑據和下載路徑...我認為您的主要問題可能是您的登錄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)
實際上沒有太多。 登錄並獲取內容。 替換該URL,我用您感興趣的任何東西進行了測試。您提供的URL給了我404。干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.