[英]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.