【发布时间】:2021-02-15 04:10:01
【问题描述】:
我一直致力于从 python 抓取网页,我想从网站的 URL 创建一个数据框。该文件的数据格式为.ods。我尝试使用 beautifulsoup 将 .ods 文件下载到计算机,然后读取它以创建数据框。该文件本身包含一个必须删除的标题。我通过这种方法取得了成功,我的代码附在下面。
from pandas_ods_reader import read_ods
import bs4
import requests
import pandas as pd
url = "https://www.gov.uk/government/statistics/transport-use-during-the-coronavirus-covid-19-pandemic"
html = requests.get(url)
soup = bs4.BeautifulSoup(html.text, "html.parser")
i=0
for link in soup.find_all('a', href=True):
i+=1
href = link['href']
if any(href.endswith(x) for x in ['.ods']):
#print(href)
file_data = requests.get(href).content
with open('data.ods', "wb") as file:
file.write(file_data)
df = read_ods('data.ods', 1, headers=False)[6:-44]
df.index = range(0, 346)
df.columns = df.iloc[0]
df.drop(0)
df
现在我想弄清楚是否可以不下载.ods文件直接实现这一点。如果有一种方法可以直接从网页中可用的 .ods 文件创建数据框,那将符合我的目的。如果可以的话,请建议一个合适的代码
【问题讨论】:
-
将开头部分缩短为
soup.select_one('.thumbnail')['href']
标签: python web-scraping beautifulsoup