[英]Beautifulsoup scraping specific table in page with multiple tables
import requests
from bs4 import BeautifulSoup
results = requests.get("https://en.wikipedia.org/wiki/List_of_multiple_Olympic_gold_medalists")
src = results.content
soup = BeautifulSoup(src, 'lxml')
trs = soup.find_all("tr")
for tr in trs:
print(tr.text)
這是我從“https://en.wikipedia.org/wiki/List_of_multiple_Olympic_gold_medalists”頁面為抓取表編寫的代碼
如果我只針對“職業生涯最多奧運金牌榜”中的表格,我該如何指定我需要的表格? 有 2 個可排序的jquery-tablesorter
所以我不能使用 class 屬性來選擇我需要的表。
還有一個問題,如果我知道我正在抓取的頁面包含很多表格,而我需要的表格總是在 1 row
有 10 td
,我可以有類似的東西嗎
If len(td) == 10:
print(tr)
提取我想要的數據
代碼更新:
from bs4 import BeautifulSoup
results = requests.get("https://en.wikipedia.org/wiki/List_of_multiple_Olympic_gold_medalists")
src = results.content
soup = BeautifulSoup(src, 'lxml')
tbs = soup.find("tbody")
trs = tbs.find_all("tr")
for tr in trs:
print(tr.text)
我有一個解決方案,不是一個好的解決方案,只是從我需要的頁面中提取第一個表格,歡迎任何建議/改進!
謝謝你。
要僅獲取第一個表,您可以使用 CSS Selector nth-of-type(1)
:
import requests
from bs4 import BeautifulSoup
URL = "https://en.wikipedia.org/wiki/List_of_multiple_Olympic_gold_medalists"
soup = BeautifulSoup(requests.get(URL).content, "html.parser")
table = soup.select_one("table.wikitable:nth-of-type(1)")
trs = table.find_all("tr")
for tr in trs:
print(tr.text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.