【问题标题】:Cannot scrape 'value' from a hidden tag using BeautifulSoup无法使用 BeautifulSoup 从隐藏标签中刮取“价值”
【发布时间】:2021-08-07 18:44:09
【问题描述】:

我试图从这个链接中获取 6,550 英镑的基本价格:https://www.plates4less.co.uk/private-plate_o/CSG1S 它位于一个名为 BasePrice 的隐藏输入中,当我查看页面源时,'6550' 位于一个名为 value 的属性中:

<input type="hidden" name="BasePrice" id="BasePrice" value="6550">

我的代码是:

url = 'https://www.plates4less.co.uk/private-plate_o/CSG1S'
req = session.get(url, headers=headers)
bsObj = BeautifulSoup(req.text, features="html.parser")
price = bsObj.find("input", {"name" : {"BasePrice"}})
print(price['value'])

但它返回KeyError: 'value'

当我运行它时(即检索标签但没有尝试访问“值”:

url = 'https://www.plates4less.co.uk/private-plate_o/CSG1S'
req = session.get(url, headers=headers)
bsObj = BeautifulSoup(req.text, features="html.parser")
price = bsObj.find("input", {"name" : {"BasePrice"}})
print(price)

我明白了:

<input id="BasePrice" name="BasePrice" type="hidden"/>

为什么我注意到可以访问value 属性?

【问题讨论】:

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


    【解决方案1】:

    您在 paga 上看到的数据是从外部 URL 加载的。要加载基本价格,您可以使用以下示例:

    import json
    import requests
    
    # CSG1S is from your base URL
    url = "https://www.plates4less.co.uk/apiv3/TransferOptions/CSG1S"
    
    data = requests.get(url).json()
    
    # uncomment to see all data:
    # print(json.dumps(data, indent=4))
    
    print(data["data"]["registrationNumber"]["displayedBPrice"])
    

    打印:

    6550.0
    

    【讨论】:

    • 谢谢!出于兴趣,您如何知道它是由外部 URL 提供并找到它来自的 url?
    • @Chris 我在查看 Firefox 开发者工具->网络选项卡时找到了 URL。该页面正在连接的所有 URL。
    猜你喜欢
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多