beautifulsoup - 从 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
解决方案
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 笔记本的示例输出
推荐阅读
- python - Python中的多处理创建单个进程
- phaser-framework - 如何使用Phaser在手机上制作全屏版
- jekyll - paginator.posts 在 Github 页面上的 Jekyll-paginate-v2 中不起作用
- javascript - 无法从 chrome 扩展加载 javascript
- javascript - 内联 JS 网络扩展
- python - 按索引分配随机质心
- azure - 使用 API 在 Azure AD 中注册应用程序(应用程序注册)?
- php - 如何在while循环php中使用复选框插入数据
- flutter - 如何在颤振中创建可滚动的选项卡
- java - 如果来自 ejb 包,来自 jackson 的 @JsonIgnore 将被忽略