2 回答

TA貢獻1829條經驗 獲得超4個贊
您可以獲得sorting_1課程,因為它不存在于頁面源代碼中。您已找到表中的所有行,然后從所需的列中讀取信息。
因此,要獲取每個國家/地區的總案例,您可以使用以下代碼:
import requests
import bs4
res = requests.get('https://www.worldometers.info/coronavirus/')
soup = bs4.BeautifulSoup(res.text, 'lxml')
country_cases = soup.find_all('td', {'class': 'sorting_1'})
rows = soup.select('table#main_table_countries_today tr')
for row in rows[8:18]:
tds = row.find_all('td')
print(tds[1].text.strip(), '=', tds[2].text.strip())

TA貢獻1883條經驗 獲得超3個贊
這些類似乎sorting_X是由 javascript 添加的,因此它們不存在于原始 html 中。
但是,該表確實存在,因此我建議循環遍歷類似于此的表行:
table_rows = soup.find("table", id="main_table_countries_today").find_all("tr")
for row in table_rows:
? ??
? ? name = "unknown"
? ? # Find country name
? ? for td in row.find_all("td"):
? ? ? ? if td.find("mt_a"): # This kind of link apparently only exists in the "name" column
? ? ? ? ? ? name = td.find("a").text
? ? # Do some more scraping
警告,我有一段時間沒有喝湯了,所以這可能不是 100% 正確。你明白了。
添加回答
舉報