首页 > 解决方案 > 从 html 文本中提取表格

问题描述

我正在尝试从页面中提取文本并将其保存为数据框。该页面未格式化为标签,因此 pandas 无法直接读取它。我尝试使用 bs4 但无法提取确切的 URL。

from bs4 import BeautifulSoup

html = requests.get('https://s3.amazonaws.com/todel162/veryimp/claps-0001.html')
soup = BeautifulSoup(html.text, "lxml") 


links = soup.find_all('li')

import pandas as pd
df = pd.DataFrame(links)

我期望 4 列的数据框,像这样......

vote title date url
1 How a TV Sitcom Triggered the Downfall of Western Civilization 2016-03-23 12:23 https://medium.com/p/how-a-tv-sitcom-triggered-the-downfall-of-western-civilization-336e8ccf7dd0

标签: beautifulsouplxml

解决方案


soup.find_all('li')只返回li页面中的所有标签。您需要做的是从每个li标签(例如投票、标题、日期和网址)中获取相关信息,然后将其保存到可能的列表列表中。然后您可以将其转换为数据框。您可以通过标签的'href'属性使用 BeautifulSoup 获取 url 。'a'

from bs4 import BeautifulSoup
import requests
import pandas as pd
html = requests.get('https://s3.amazonaws.com/todel162/veryimp/claps-0001.html')
soup = BeautifulSoup(html.text, "lxml")
links = soup.find_all('li')
final_list=[]
for li in links:
    votes=li.contents[0].split(' ')[0]
    title=li.find('a').text
    date=li.find('time').text
    url=li.find('a')['href']
    final_list.append([votes,title,date,url])
df = pd.DataFrame(final_list,columns=['Votes', 'title', 'Date','Url'])
print(df)
#just df if in Jupyter notebook

Jupyter 笔记本的示例输出

在此处输入图像描述


推荐阅读