xpath 兼容问题

在 scrapy shell 中 xpath 能提取到结果, 然而,spider.py 中不能提取到结果,可能原因是 scrapy 不支持其中 xpath 的某些特性。

解决方法

重写一个 xpath, 尽量不要使用高级的 xpath 功能

1
2
3
"//div[starts-with(@class, 'grid_7')]//a[text() != ' Listing by Chemical Class']//@href"

'//*[@id="hero"]/div/div/div//a/@href'
  • 例如,上述两个 xpath 在 scrapy shell 中都能使用, 第一个在 spider 中却 不能使用

再次爬取,提交 request

scrapy.Request(url, callback=parse)

url 必须是绝对 url

response.follow(url, callback=parse)

  • url 可以是相对 url
  • url 可以是 css selector object

提交方法

yield scrapy.Request(url, callback=parse)

注意:

yield 不可缺少,因为这样生成的大概 genarator
yield 提交 scrapy 才能感知到

scrapy log

self.logger

1
2
3
4
5
6
7
8
import scrapy

class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['https://scrapinghub.com']

def parse(self, response):
    self.logger.info('Parse function called on %s', response.url)

response

路径

scrapy.http.response.Response

方法

Response.urljoin(relativeUrl)

make a absolute url

属性

Response.body

Response.url