繁体   English   中英

BeautifulSoup object 内容到字符串

[英]BeautifulSoup object contents to string

我正在从 web 页面中提取表和表 header 元素。 表格元素已被提取,没有任何问题。 但是,我无法将 h2 class 提取到单独的字符串中。 我可以将全部导入为 beautifulsoup 对象或作为包含所有 h2 元素的一个长字符串。 如何将元素作为单独的字符串对象提取到表或列表中?

scr = 'https://tv.varsity.com/results/7361971-2022-spirit-unlimited-battle-at-the- 
boardwalk-atlantic-city-grand-ntls/31220'
    
scr1 = requests.get(scr)
soup = BeautifulSoup(scr1.text, "html.parser")
sp3 = soup.find(class_="full-content").find_all("h2")

到目前为止,这是我尝试过的两种方法。

comp = pd.DataFrame(sp3[0], dtype=str)
div1a = div.drop(div.iloc[0].name)
div2a = div1a.drop(div1a.iloc[0].name)

也使用 for 循环

data = []
for a in soup.find(class_="full-content").find_all("h2"):
    a = str(a.text)
    data.append(a)

x = ",".join(map(str, data))
print(x)

感谢您的帮助!

您可以使用列表推导来获取列表中每个 h2 元素的文本,或者使用 for 循环遍历 h2 元素。

import requests
from bs4 import BeautifulSoup

url = 'https://tv.varsity.com/results/7361971-2022-spirit-unlimited-battle-at-the-boardwalk-atlantic-city-grand-ntls/31220'
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
sp3 = soup.find(class_="full-content").find_all("h2")
headers = [elt.text for elt in sp3]
print(headers)

Output:

['2022 Spirit Unlimited: Battle at the Boardwalk Atlantic City Grand Ntls Nationals Results',
'Level 5 & 6 Results', 'L5 Junior', ...
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM