无法使用python脚本从URL下载csv文件
问题描述:
我正在访问带有用户名和密码的url以下载csv并使用今天的日期和时间保存文件,页面上只有一个下载链接。无法使用python脚本从URL下载csv文件
有没有什么办法可以实现通过Python
这个任务我使用这个脚本下面我看到了打印输出。但是我怎样才能下载网页上的下载csv按钮。通常当我点击下载csv按钮时,它会要求我保存文件。
import re
import requests
from bs4 import BeautifulSoup
url = 'https://url.com'
login_data = dict(login='[email protected]', password='password-g')
session = requests.session()
link = 'https://url.com'
r = requests.get(link)
soup = BeautifulSoup(r.text, "html.parser")
for i in soup.find_all('a', {'class': "app-btn-down"}):
print(re.search('http://.*\b_file', i.get('href')).group(0)) # the CSV file name is b_file
print ("r.text")
由于我是python的新手,所以请原谅我对我的错误解释。
答
这主要是伪代码,因为我不知道html数据,但我想你会明白。
首先,您必须提交数据才能在会话中获得必要的cookie(可以使用s.cookies
查看cookie)。请记住,除login
和password
之外,您可能还需要提交更多字段。使用此会话处理所有请求。
然后,您可以通过bs4
获取csv链接,假设它不是由js生成的,否则您可能必须使用selenium
。
import requests
from bs4 import BeautifulSoup
from time import gmtime, strftime
import os
s = requests.session()
url = 'https://url.com'
login_data = dict(login='[email protected]', password='password-g')
s.post(url, data=login_data)
link = 'https://url.com'
r = s.get(link)
soup = BeautifulSoup(r.text, "html.parser")
csv_link = soup.find('a', {'class':'app-btn-down', 'href':lambda h:'b_file' in h})['href']
csv_file = s.get(csv_link).text
最后,你可以得到的日期和时间gmtime
,并使用strftime
格式化。
date_time = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
path = os.path.join('/some/dir', date_time)
with open(path, 'w') as f:
f.write(csv_file)
你必须提交'login_data' –
我所提到的'在第6行login_data' – Mongrel
您已经定义了'login_data' IL 6号线,但你不提交。此外,您似乎应该请求''app-btn-down''链接。如果你能分享真正的'url',我可能会帮助更多。 –