首页 > 解决方案 > 抓取网站时访问变量

问题描述

我目前正在尝试抓取一个网站(下面代码中的 url),但是当我拉出我想要使用的 html 部分时,我得到的只是我正在寻找的信息的变量名。当我手动检查页面的 html 时,变量的实际值是存在的,但我假设当我抓取页面时,我看到的只是网站引用了其他地方的变量。

我希望有人可以帮助我尝试访问此信息。我曾尝试使用 selenium 抓取网站的 html,但是我似乎只是返回了使用请求时抓取的相同 html(也许我做错了)。

这是我的代码的改进版本:

import scrapy
from scrapy import Selector
import requests

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}


url = 'https://groceries.aldi.ie/en-GB/drinks/Beer-Ciders?sortDirection=asc&page=1'
html = requests.get(url, headers=headers).content
sel = Selector(text=html)

html_info = (sel.xpath('//*[@id="vueSearchResults"]/div/div[1]/div/div[4]/a').extract())

print(html_info)

然后返回以下内容:

['<a data-qa="search-product-title" v-bind:href="Product.Url" v-bind:title="Product.FullDisplayName" v-bind:data-productid="Product.ProductId" data-oc-click="searchProductClick" class="p text-default-font"> {{Product.DisplayName}} </a>']

我想从中获取“Product.FullDisplayName”的实际值。如果有人能指出正确的方向来访问此变量的信息,或抓取网站 html 的方法,我将不胜感激 - 正如用户浏览网页所看到的那样。谢谢!

标签: pythonhtmlweb-scraping

解决方案


我认为您可以使用Scrapyrequests库,因为它们在下载页面时都有相同的用途。

本网站不通过单一 API 提供完整数据。您可以使用此 url 获取大部分数据,如产品名称、url、图像和尺寸https://groceries.aldi.ie/en-GB/drinks/Beer-Ciders?sortDirection=asc&page=1。但是,对于价格和单价,您必须通过此 API 发送 POST 请求 https://groceries.aldi.ie/api/product/calculatePrices以及传递请求标头和有效负载。

仅用于演示,以下代码将为您提供产品名称。同样,您可以遍历其他字段来获取数据。

代码

import requests
from lxml import html
import json

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}


url = 'https://groceries.aldi.ie/en-GB/drinks/Beer-Ciders?sortDirection=asc&page=1'

response = requests.get(url, headers=headers)
tree = html.fromstring(response.text)
data = tree.xpath('//div[@class="products-search-results"]/@data-context')
product_name = json.loads(data[0])

for each_product in product_name['SearchResults']:
    print(each_product['FullDisplayName'])

输出(截断)

American Style Premium Lager 4 X 500ml Brookston
Traditional Irish Cider Apple Cider 8 X 500ml Cullen's
Premium Lager 500ml San Marcos
Cider Apple 8 X 500ml Orchard Thieves
Hop House500ml Can 8 X 500ml Guinness

推荐阅读