带有Python请求/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中下载文件,我只需要单击文件的名称,但是我无法使用请求和美丽的套件来完成此操作。我的整个代码看起来像这样:

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

这是我所处的位置,只能检索文件

您是否尝试使用请求直接访问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

我希望这能解决您的问题。

最新更新