div
withlistings
类 (and ) 中的内容id
通过 XHR 请求异步加载。换句话说,Scrapy
获取的 html 代码不包含它:
$ scrapy shell http://groceries.asda.com/asda-webstore/landing/home.shtml?cmpid=ahc--ghs-d1--asdacom-dsk-_-hp#/shelf/1215337195041/1/so_false
>>> response.xpath('//div[@id="listings"]')
[]
使用浏览器开发人员工具,您可以看到带有一堆 GET 参数的请求转到http://groceries.asda.com/api/items/viewitemlist url。
一种选择是模拟该请求并解析生成的 JSON:

如何做到这一点实际上是另一个问题的一部分。
这是使用selenium
包的一种可能的解决方案:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://groceries.asda.com/asda-webstore/landing/home.shtml?cmpid=ahc--ghs-d1--asdacom-dsk-_-hp#/shelf/1215337195041/1/so_false')
div = driver.find_element_by_id('listings')
for item in driver.find_elements_by_xpath('//div[@id="listings"]//a[@title]'):
print item.text.strip()
driver.close()
印刷:
Kellogg's Coco Pops
Kelloggs Rice Krispies
Kellogg's Coco Pops Croco Copters
...