【问题标题】:Can't scrape some fields from a webpage using requests无法使用请求从网页中抓取某些字段
【发布时间】:2020-12-02 08:13:24
【问题描述】:

我正在尝试找到一种使用请求从网页中获取三个字段的方法。如果我尝试像 this 一样使用 selenium,我可以相应地获取它们。但是,我不想走那条路。相反,我想使用请求从该网页中获取三个字段,因为大多数时候有替代方案,如hidden apiscript tag 等。我尝试使用开发工具搜索它们,但失败得很惨,所以我想寻求任何帮助。

website link

我追求的三个领域:

我试过了:

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)

如何使用请求从该站点获取这三个字段?

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup python-requests


    【解决方案1】:

    抓取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
    

    【讨论】:

    • 每个数字后面的ks 使得在开发工具中很难找到它们。它们确实在脚本标记的页面源中。非常感谢@jizhihaoSAMA 的解决方案。它完美地做到了。
    猜你喜欢
    • 2020-08-30
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多