请求-html 找不到页面元素

requests-html not finding page element

所以我正在尝试导航到这个 url:https://www.instacart.com/store/wegmans/search_v3/horizon%201%25 并使用 class item-name item-row 从 div 抓取数据。但是有两个主要问题,第一个是 instacart.com 需要登录才能到达 url,第二个是大部分页面都是用 javascript 生成的。

我相信我已经解决了第一个问题,因为我的 session.post(...) 收到了 200 响应代码。我也很确定 r.html.render() 应该通过在我抓取之前渲染 javascript 生成的 html 来解决第二个问题。不幸的是,我的代码中的最后一行只返回一个空列表,尽管事实上 selenium 可以毫无问题地获取这个元素。有谁知道为什么这不起作用?

from requests_html import HTMLSession
from bs4 import BeautifulSoup
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}
session = HTMLSession()
res1 = session.get('http://www.instacart.com', headers=headers)
soup = BeautifulSoup(res1.content, 'html.parser')
token = soup.find('meta', {'name': 'csrf-token'}).get('content')
data = {"user": {"email": "alexanderjbusch@gmail.com", "password": "password"},
        "authenticity_token": token}
response = session.post('https://www.instacart.com/accounts/login', headers=headers, data=data)
print(response)
r = session.get("https://www.instacart.com/store/wegmans/search_v3/horizon%201%25", headers=headers)
r.html.render()
print(r.html.xpath("//div[@class='item-name item-row']"))

使用请求模块和 BeautifulSoup 登录后,您可以使用我已经在评论中建议的 link 来解析 json 中可用的所需数据。以下脚本应为您提供相关产品的名称、数量、价格和 link。您只能使用下面的脚本获得 21 个产品。此 json 内容中有一个分页选项。您可以通过使用该分页来获得所有产品。

import json
import requests
from bs4 import BeautifulSoup

baseurl = 'https://www.instacart.com/store/'
data_url = "https://www.instacart.com/v3/retailers/159/module_data/dynamic_item_lists/cart_starters/storefront_canonical?origin_source_type=store_root_department&tracking.page_view_id=b974d56d-eaa4-4ce2-9474-ada4723fc7dc&source=web&cache_key=df535d-6863-f-1cd&per=30"

data = {"user": {"email": "alexanderjbusch@gmail.com", "password": "password"},
        "authenticity_token": ""}
headers = {
    'user-agent':'Mozilla/5.0',
    'x-requested-with': 'XMLHttpRequest'
}
with requests.Session() as s:

    res = s.get('https://www.instacart.com/',headers={'user-agent':'Mozilla/5.0'})
    soup = BeautifulSoup(res.text, 'lxml')
    token = soup.select_one("[name='csrf-token']").get('content')

    data["authenticity_token"] = token

    s.post("https://www.instacart.com/accounts/login",json=data,headers=headers)
    resp = s.get(data_url, headers=headers)

    for item in resp.json()['module_data']['items']:
        name = item['name']
        quantity = item['size']
        price = item['pricing']['price']
        product_page = baseurl + item['click_action']['data']['container']['path']
        print(f'{name}\n{quantity}\n{price}\n{product_page}\n')

部分输出:

SB Whole Milk
1 gal
.90
https://www.instacart.com/store/items/item_147511418

Banana
At [=11=].69/lb
[=11=].26
https://www.instacart.com/store/items/item_147559922

Yellow Onion
At .14/lb
[=11=].82
https://www.instacart.com/store/items/item_147560764