Python 使用scrapy爬网节点
我正在尝试使用scrapy从网站上抓取一些广告信息。 该网站有一些Python 使用scrapy爬网节点,python,scrapy,Python,Scrapy,我正在尝试使用scrapy从网站上抓取一些广告信息。 该网站有一些div标签,上面有class=“产品卡新的”\uuuOfstock分期付款” 当我使用: items = response.xpath("//div[contains(@class, 'product-')]") items = response.xpath("//div[contains(@class, 'product-card')]") 我得到了一些具有class属性=“产品描述”的节点,但没有“产品卡” 当我使用: i
div
标签,上面有class=“产品卡新的”\uuuOfstock分期付款”
当我使用:
items = response.xpath("//div[contains(@class, 'product-')]")
items = response.xpath("//div[contains(@class, 'product-card')]")
我得到了一些具有class属性=“产品描述”
的节点,但没有“产品卡”
当我使用:
items = response.xpath("//div[contains(@class, 'product-')]")
items = response.xpath("//div[contains(@class, 'product-card')]")
我还是一无所获
为什么会这样?您想要的数据是由Java脚本填充的 您必须使用
seleniumwebdriver
来提取数据
如果您想事先检查是否正在使用javascript填充数据,请打开一个scrapy shell并尝试提取数据,如下所示
scrapy shell 'http://www.lazada.vn/dien-thoai-may-tinh-bang/?ref=MT'
>>>response.xpath('//div[contains(@class,"product-card")]')
输出:
[]
现在,如果在浏览器中使用相同的Xpath并得到如下结果:
然后使用脚本填充数据,并且必须使用selenium来获取数据
以下是使用selenium提取数据的示例:
import scrapy
from selenium import webdriver
from scrapy.http import TextResponse
class ProductSpider(scrapy.Spider):
name = "product_spider"
allowed_domains = ['lazada.vn']
start_urls = ['http://www.lazada.vn/dien-thoai-may-tinh-bang/?ref=MT']
def __init__(self):
self.driver = webdriver.Firefox()
def parse(self, response):
self.driver.get(response.url)
page = TextResponse(response.url, body=self.driver.page_source, encoding='utf-8')
required_data = page.xpath('//div[contains(@class,"product-card")]').extract()
self.driver.close()
以下是一些“硒蜘蛛”的例子:
正如前面的回答中所指出的,您试图获取的内容是使用javascript动态生成的。如果性能对您来说不是什么大问题,那么您可以使用Selenium模拟真实用户并与站点交互。同时,您可以让Scrapy为您获取数据
如果你想得到一个类似的例子,请考虑这个教程:
谢谢,但是我得到了Eror:NAMEOrror:全局名称“TrimeRebug”没有定义。