无法使用BeautifulSoup和Requests抓取下拉菜单

时间:2019-10-08 18:59:18

标签: python web-scraping beautifulsoup python-requests

我想在百年灵网站的产品页面上抓取各种信息。

示例页面:https://www.breitling.com/gb-en/watches/navitimer/b01-chronograph-46/AB0127211C1A1/

我在刮擦“ ADD TO BAG”按钮上方的下拉菜单中给出的表带材料时遇到麻烦(示例中为“ steel 1.4435”)。

我想要的特定元素是:

<small class="dd-selected-description dd-desc dd-selected-description-truncated">Steel 1.4435</small>

但是,这在我的GET请求的响应中未返回。与<small>标签最接近的元素是带有<div>的{​​{1}}元素。

但是,当调用id='strap-selector-list'时,它会显示soup.find(id='strap-selector-list')不包含任何内容。

<div>

返回

import requests
from bs4 import BeautifulSoup

url = 'https://www.breitling.com/gb-en/watches/navitimer/b01-chronograph-46/AB0127211C1A1/'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')

soup.find(id='strap-selector-list')

如何获得内部的信息(如打开检查器时所显示的那样?)

Screenshot of page with inspector open highlighting areas of interest

我尝试过的事情:

  1. 欺骗标题。我在开发人员工具的“网络”标签中复制/粘贴了所有请求标头(除cookie之外)。我在GET请求中使用了它们(为简洁起见仅包含更改的行)
<div id="strap-selector-list"></div>
  1. 已检查XHR请求。页面加载时只有3个。一种是关于结帐篮的状态,一种是关于零售商的信息,例如商店位置,另一种是status.php,它给出404错误。

    如果单击下拉菜单,则不会发送任何XHR请求。

    如果您单击下拉菜单中的任何项目,则会转到该项目的产品页面。

  2. 使用不同的解析器,例如html.parser没有区别

  3. 在标题中添加cookie并执行正常的GET请求,也没有区别
  4. 首先创建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) ,然后在有session = requests.Session()和没有r = session.get(url)的情况下进行headers=headers都是无效的。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您要查找的数据位于script元素下。

您需要做的就是加载作为脚本主体返回的JSON并遍历字典。

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]))

输出

https://pastebin.com/kGhMQt61