【问题标题】:Python request module can't find data attribute on websitePython请求模块在网站上找不到数据属性
【发布时间】:2020-06-09 03:03:25
【问题描述】:

我正在尝试使用 python 中的 RequestsBeautifulSoup 模块在公共网站中请求特定的数据属性。网站标签中的数据属性没有任何价值,但我想我可以使用代码的 title 部分来请求它。

import requests
from bs4 import BeautifulSoup
URL = 'https://www.oneplus.com/ca_en/oneplus-7pro?from=op7pro_header'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}

page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')

title = soup.find(attrs={"data-v-5b5a108c": True})

print(title)

当我使用具有值的数据属性请求父标记时,我正在寻找的标记不会出现。为什么我看不到?我是疯了还是这不是它的工作原理?

【问题讨论】:

    标签: python html beautifulsoup python-requests


    【解决方案1】:

    此页面上的 HTML 元素是动态创建的,因此 BeautifulSoup 看不到它们。但是数据在页面里面是以Json格式存储的:

    import json
    import requests
    from bs4 import BeautifulSoup
    
    
    url = 'https://www.oneplus.com/ca_en/oneplus-7pro?from=op7pro_header'
    soup = BeautifulSoup(requests.get(url).content, 'html.parser')
    
    data = json.loads(soup.select_one('#data-device').contents[0])
    
    # uncomment this to print all data:
    # print(json.dumps(data, indent=4))
    
    print(data['steps']['options'][0]['label'])
    

    打印:

    Mirror Gray
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多