如何在请求中获得深层嵌套的类

时间:2019-07-03 05:49:01

标签: python html nested python-requests

我有一个脚本,该脚本使用请求来获取HTML,如下所示: r = session.get("https://www.instacart.com/store/wegmans/search_v3/horizon%201%25", headers=headers)

并嵌套在该网页的深处(约26层深度)是以下元素<span>$5.59</span>,我要对其进行抓取。接下来的两个元素是<span class=""></span><div class="item-price" style="flex: 1 1 0%;"></div>,因此我首先想到的是,如果我可以找到“ item-price”类,则可以往下两层走,然后尝试以下代码:

tree = html.fromstring(r.content)
result = tree.xpath("//div[@class='item-price']")

但是当我打印结果时,它只显示一个空列表。我尝试了许多其他方式,并且我的理论是,我使用xpath的方式不会比第一层元素更深入,因为在我指定body // div // etc排序的地方使用了客观xpath的工作。

有没有一种方法可以遍历其中的所有元素以找到“ item-price”类,或者有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

Instacart的页面是动态生成的,requests不执行javascript。该项目列表在初始页面加载中不存在,仅在之后通过javascript和ajax添加。 (您可以通过右键单击页面并选择“查看源代码”来进行检查。)

实际数据是从另一个动态生成的url加载的,该URL类似于:

https://www.instacart.com/v3/retailers/42/module_data/dynamic_item_lists/delivery_promotion?list_ref=unilevermainstream0719&origin_source_type=department&scores=&tracking.page_view_id=7f55bb7a-00bf-4fa8-ac48-fd9e0f10cc59&source=web&cache_key=f90e09-7286-f-5bb&per=30