Python 无法使用BeautifulSoup和请求刮取下拉菜单
我想从百年灵网站的产品页面上搜寻各种信息 示例页面: 在“添加到包”按钮上方的下拉菜单中给出的手表表带材料(示例中的“steel 1.4435”)上,我很难刮取 我想要的具体元素是:Python 无法使用BeautifulSoup和请求刮取下拉菜单,python,web-scraping,beautifulsoup,python-requests,Python,Web Scraping,Beautifulsoup,Python Requests,我想从百年灵网站的产品页面上搜寻各种信息 示例页面: 在“添加到包”按钮上方的下拉菜单中给出的手表表带材料(示例中的“steel 1.4435”)上,我很难刮取 我想要的具体元素是: <small class="dd-selected-description dd-desc dd-selected-description-truncated">Steel 1.4435</small> 返回 <div id="strap-selector-list"><
<small class="dd-selected-description dd-desc dd-selected-description-truncated">Steel 1.4435</small>
返回
<div id="strap-selector-list"></div>
session=requests.session()
并使用和不使用headers=headers
执行r=session.get(url)
也不起作用非常感谢您的帮助 您要查找的数据位于
脚本
元素下
您所需要做的就是加载作为脚本主体返回的JSON并遍历dict
import requests
from bs4 import BeautifulSoup
import json
import pprint
url = 'https://www.breitling.com/gb-en/watches/navitimer/b01-chronograph-46/AB0127211C1A1/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html')
script = soup.find(id='app-reference-versions')
pprint.pprint(json.loads(script.contents[0]))
输出
@DarkLeader我正在扫描页面源代码,寻找“1.4435”之类的词是的,我在html中找到了下拉菜单的位置,但像OP一样,我无法获取内容,也找不到任何idtags@DarkLeader执行“查看源代码”并查找
script type=“application/json”
如何查看源代码?@DarkLeader Yes do control+F并键入type=“application/json”
或应用程序参考版本
。然后您将看到脚本元素
headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cache-control': 'max-age=0',
'dnt': '1',
'referer': 'https://www.breitling.com/gb-en/watches/navitimer/?search%5Bref%5D=&search%5Bsorting%5D=newest',
'sec-fetch-mode': 'navigate, same-origin, cors',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest'
}
r = requests.get(url, headers=headers)
import requests
from bs4 import BeautifulSoup
import json
import pprint
url = 'https://www.breitling.com/gb-en/watches/navitimer/b01-chronograph-46/AB0127211C1A1/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html')
script = soup.find(id='app-reference-versions')
pprint.pprint(json.loads(script.contents[0]))