亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Python 抓取“sorting_1”類中的內容?

如何使用 Python 抓取“sorting_1”類中的內容?

慕田峪7331174 2023-04-25 17:45:17
我得到了一個制作 covid 追蹤器的項目。我決定通過網站 ( https://www.worldometers.info/coronavirus/ ) 抓取一些元素。我對 python 很陌生,所以決定使用 BeautifulSoup。我能夠抓取基本元素,如總案例、活躍案例等。但是,每當我嘗試獲取國家名稱或數字時,它都會返回一個空列表。即使存在類“sorting_1”,它仍然返回一個空列表。有人可以指導我哪里出錯了嗎?這是我想要抓住的東西:<td style="font-weight: bold; text-align:right" class="sorting_1">4,918,420</td>這是我當前的代碼:import requestsimport bs4#making a request and a soupres = requests.get('https://www.worldometers.info/coronavirus/')soup = bs4.BeautifulSoup(res.text, 'lxml')#scraping starts heretotal_cases = soup.select('.maincounter-number')[0].texttotal_deaths = soup.select('.maincounter-number')[1].texttotal_recovered = soup.select('.maincounter-number')[2].textactive_cases = soup.select('.number-table-main')[0].textcountry_cases = soup.find_all('td', {'class': 'sorting_1'})
查看完整描述

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())


查看完整回答
反對 回復 2023-04-25
?
白板的微信

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% 正確。你明白了。


查看完整回答
反對 回復 2023-04-25
  • 2 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號