[英]Can't scrape some fields from a webpage using requests
我正在嘗試找到一種使用請求從網頁中獲取三個字段的方法。 如果我使用 selenium 嘗試這樣,我可以相應地獲取它們。 但是,我不希望 go 這條路線。 相反,我想使用請求從該網頁中獲取三個字段,因為大多數情況下都有替代方案,例如hidden api
, script tag
etc。 我嘗試使用開發工具搜索它們,但失敗得很慘,所以我想尋求任何幫助。
我追求的三個領域:
我試過:
import requests
from bs4 import BeautifulSoup
link = "https://www.gofundme.com/f/toronto-tiny-shelters"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"}
with requests.Session() as s:
r = s.get(link,headers=headers)
soup = BeautifulSoup(r.text,"lxml")
donors = soup.select_one("[data-element-id='btn_donors'] > span").text
shares = soup.select_one("span.text-stat:has(> span:contains('shares')) > span.text-stat-value").text
followers = soup.select_one("span.text-stat:has(> span:contains('followers')) > span.text-stat-value").text
print(donors,shares,followers)
如何使用請求從該站點獲取這三個字段?
刮取 API 將得到每個數據的確切數量。
試試下面的代碼:
import requests
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36',
}
response = requests.get('https://gateway.gofundme.com/web-gateway/v1/feed/toronto-tiny-shelters/counts', headers=headers)
d = response.json()["references"]["counts"]
print("donors: ", d['total_donations'])
print("shares: ", d['social_share_total'])
print("followers: ", d['campaign_hearts'])
結果:
donors: 3742
shares: 4369
followers: 3708
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.