首页 > 解决方案 > 使用 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

这就是我所在的位置,它只是检索文件

标签: pythonbeautifulsouppython-requests

解决方案


您是否尝试使用 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

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


推荐阅读