账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    scrapy框架 xpath语法的一些疑问
    • 2020-01-01 00:00
    • 10
    44
    0

    在看《精通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()呢?

    这一.之差是为什么?

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部