python - 使用 python requests/beautifulsoup 从库中检索 .CSV
问题描述
初学者在这里。我正在尝试从 python 中检索 .csv。经过多次 .post 和 .get 终于到了可以下载文件的地步。在网页中,为了下载文件,有一个 url 包含所有这样的文件
https://example.com/storage/exports/443/
其中有多个 .csv 文件,格式如下:
<a href="./2019-07-29%2007:59:26.csv">2019-07-29 07:59:26.csv</a>
我已经有了我想要的文件的href,这是最后一个
download=soup.find_all('a')[-1]
要下载 url 中的文件,我只需要单击文件名,但我无法通过 requests 和 beautifulsoup 来完成此操作。我的整个代码如下所示:
import requests
from bs4 import BeautifulSoup
import html5lib
logind={'_token':'','email':'example@email','password':'123'}
#login
with requests.Session() as s:
url='https://example.com'
header={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'}
r=s.get(url,headers=header)
soup=BeautifulSoup(r.content, 'html5lib')
logind['_token']=soup.find('input',attrs={'name':'_token'})['value']
r=s.post(url,data=logind,headers=header,verify=True)
r=s.get('https://example.com/reports')
r=s.post('https://example.com/reports2',data= {'id':'165'})
r=s.post('https://example.com/reports/generate',data=dat)
#multiple steps to generate the report
r=s.get('https://example.com/storage/exports/443')
#url where file is
soup=BeautifulSoup(r.content,'html5lib')
download=soup.find_all('a')[-1]
#href of file i need
这就是我所在的位置,它只是检索文件
解决方案
您是否尝试使用 requests 直接访问 href?它似乎是一个相对路径,因此您可以获取原始端点并附加到它。
使用 pandas,您可以直接读取并返回(如果需要,甚至可以保存)
所以从你的代码
### what you have done before...
download=soup.find_all('a')[-1]
yourFile = requests.get(endpoint+download).text
import pandas as pd
df = pd.read_csv(yourfile)
df.to_csv('myreport.csv',index=false,sep='\t')
return df
我希望这能解决你的问题。
推荐阅读
- file - golang:监视(和读取)为写入而打开的文件
- visual-studio - 更改展开的 dgml 节点的颜色
- android - Android AWS Appsync 订阅不会触发事件
- javascript - 在画布中添加 elem 会删除背景并将其自身呈现在白色画布上
- python - 无法导入 BACKEND 'channels_redis.core.RedisChannelLayer' Django Channels 2.1.2
- java - Facebook api 中的某些广告素材缺少链接 URL 数据
- c++ - 如何在头文件中定义结构的元素?
- node.js - Twilio Taskrouter:如何在工作流配置中实现 WorkerSid 的“不联系”列表?
- whitespace - 将 xinclude 与 docbook 一起使用时保留空格
- c++ - 我可以在循环内对 std::string 的一部分进行引用并使其在外部可用吗?