Scrapy无法刮取项目,xpath不工作
我花了很多时间试图用scrapy搜集信息,但没有成功。 我的目标是浏览分类,并为每个项目刮标题,价格和标题的href链接 问题似乎来自parse_items函数。我已经用firepath检查了xpath,并且我能够根据需要选择项目,所以我可能不知道scrapy是如何处理xpath的 这是我的密码Scrapy无法刮取项目,xpath不工作,xpath,scrapy,Xpath,Scrapy,我花了很多时间试图用scrapy搜集信息,但没有成功。 我的目标是浏览分类,并为每个项目刮标题,价格和标题的href链接 问题似乎来自parse_items函数。我已经用firepath检查了xpath,并且我能够根据需要选择项目,所以我可能不知道scrapy是如何处理xpath的 这是我的密码 from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import Selector
from ..items import electronic_Item
class robot_makerSpider(CrawlSpider):
name = "robot_makerSpider"
allowed_domains = ["robot-maker.com"]
start_urls = [
"http://www.robot-maker.com/shop/",
]
rules = (
Rule(LinkExtractor(
allow=(
"http://www.robot-maker.com/shop/12-kits-robots",
"http://www.robot-maker.com/shop/36-kits-debutants-arduino",
"http://www.robot-maker.com/shop/13-cartes-programmables",
"http://www.robot-maker.com/shop/14-shields",
"http://www.robot-maker.com/shop/15-capteurs",
"http://www.robot-maker.com/shop/16-moteurs-et-actionneurs",
"http://www.robot-maker.com/shop/17-drivers-d-actionneurs",
"http://www.robot-maker.com/shop/18-composants",
"http://www.robot-maker.com/shop/20-alimentation",
"http://www.robot-maker.com/shop/21-impression-3d",
"http://www.robot-maker.com/shop/27-outillage",
),
),
callback='parse_items',
),
)
def parse_items(self, response):
hxs = Selector(response)
products = hxs.xpath("//div[@id='center_column']/ul/li")
items = []
for product in products:
item = electronic_Item()
item['title'] = product.xpath(
"li[1]/div/div/div[2]/h2/a/text()").extract()
item['price'] = product.xpath(
"div/div/div[3]/div/div[1]/span[1]/text()").extract()
item['url'] = product.xpath(
"li[1]/div/div/div[2]/h2/a/@href").extract()
#check that all field exist
if item['title'] and item['price'] and item['url']:
items.append(item)
return items
感谢您的帮助您的蜘蛛中的XPath确实有缺陷 您的第一个产品xpath确实可以工作,但不够明确,可能很容易失败。虽然产品细节XPath根本不起作用 我已经让它与:
products = response.xpath("//div[@class='product-container']")
items = []
for product in products:
item = dict()
item['title'] = product.xpath('.//h2/a/text()').extract_first('').strip()
item['url'] = product.xpath('.//h2/a/@href').extract_first()
item['price'] = product.xpath(".//span[contains(@class,'product-price')]/text()").extract_first('').strip()
所有现代网站都有非常友好的解析html源代码(因为它们需要自己解析以获得奇特的css样式和javascript功能)
因此,通常您应该查看要使用浏览器检查工具(右键单击->检查元素)提取的节点的类和id名称,而不是使用一些自动选择工具。它更可靠,一旦掌握了窍门,就不需要做更多的工作。谢谢你,伙计!从这里开始我会小心的。你能解释一下直接从响应中查找xpath而不是使用选择器(响应)方法有什么影响吗?@artfilstatistiseu本质上是一样的。响应对象使用自身创建
选择器
,这样您就可以方便地快捷访问响应。选择器
,而不必每次自己创建选择器。而response.xpath
是response.selector.xpath
的快捷方式。这个方法非常简单,你可以自己给它一个峰值:)