在 BeautifulSoup 中创建行和列
Posted
技术标签:
【中文标题】在 BeautifulSoup 中创建行和列【英文标题】:Create Rows and Columns in BeautifulSoup 【发布时间】:2021-12-30 05:42:44 【问题描述】:下面是代码python代码输出。我想在数据框中按行和列输出:
response = requests.get(source_data)
soup = BeautifulSoup(response.text, "html.parser")
States = soup.find_all('div',class_ = 'card bg-darker p-3 mb-3')
for item in States :
state_name = item.find(class_='fw-bold fs-5 mb-2').text
vaccinated_per = item.find(class_='col-3 text-end fs-5 ff-s text-success').text
print(state_name,vaccinated_per)
输出:
法兰德斯 80.24%
瓦隆 70.00%
布鲁塞尔 56.73%
东比利时 65.11%
【问题讨论】:
请给出链接地址 covid-vaccinatie.be/en 【参考方案1】:在字典列表中收集您的信息,然后简单地从中创建一个数据框:
data = []
for item in States :
data.append(
'state_name' : item.find(class_='fw-bold fs-5 mb-2').text,
'vaccinated_per' : item.find(class_='col-3 text-end fs-5 ff-s text-success').text
)
pd.DataFrame(data)
示例
from bs4 import BeautifulSoup
import requests
import pandas as pd
headers = 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
response = requests.get('https://covid-vaccinatie.be/en', headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
States = soup.find_all('div',class_ = 'card bg-darker p-3 mb-3')
data = []
for item in States :
data.append(
'state_name' : item.find(class_='fw-bold fs-5 mb-2').text,
'vaccinated_per' : item.find(class_='col-3 text-end fs-5 ff-s text-success').text
)
pd.DataFrame(data)
输出
state_name vaccinated_per
0 Flanders 80.24%
1 Wallonia 70.00%
2 Brussels 56.73%
3 Ostbelgien 65.11%
【讨论】:
以上是关于在 BeautifulSoup 中创建行和列的主要内容,如果未能解决你的问题,请参考以下文章
Magical Record 的新手:上下文未在数据存储中创建行