scrapy框架 xpath语法的一些疑问

在看《精通python爬虫框架scrapy》的时候遇到一些小疑问。
首先需要说明一下,下面的爬虫是针对同一个示例页面的。

书中的示例代码如下,首先定义了项目的project/items.py

from scrapy.item import Item, Field
class ProjectItem(Item):
  ......
  title = Field()
  price = Field()
  ......

然后定义了一个示例爬虫project/spiders/basic.py

import scrapy
from project.item import ProjectItem
class BasicSpyder(scrapy.Spider):
  ......
  def parse(self, response):
    self.log("title %s" % response.xpath(
      '//*[@itemprop = "title"][1]/text()').extract())
    self.log("price %s" % response.xpath(
      '//*[@itemprop = "price"][1]/text()').re('[.0-9]+'))
  ......

接着书中又用ItemLoader改装了一下project/spiders/basic.py

import scrapy.loader import ItemLoader
from project.item import ProjectItem

class BasicSpyder(scrapy.Spider):
  ......
  def parse(self, response):
    p = ItemLoader(item = ProjectItem(), response = response)
    p.add_xpath('title', '//*[@itemprop = "title"][1]/text()')
    p.add_xpath('price', './/*[@itemprop = "price"][1]/text()', re = '[,.0-9]+')
  ......

为什么在使用self.log的时候pricexpath
//*[@itemprop = "price"][1]/text()

而在ItemLoaderxpath却是
.//*[@itemprop = "price"][1]/text()呢?

这一.之差是为什么?

阅读 1.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进