response.xpath("//li[@class='next']/a/@href") is not None

if  response.xpath("//li[@class='next']/a/@href") is not None :

# index list out of range


这里response.xpath("//li[@class='next']/a/@href")如果找不到的话,会返回一个空列表,但不是None

可以用  if len(response.xpath("//li[@class='next']/a/@href")): 来判断


======2017-12-16更新======

# docs.scrapy.org

# If you want to extract only first matched element, you can call the selector .extract_first()

# It returns None if no element was found.

# 上面也可以改成:

if response.xpath("//li[@class='next']/a/@href").extract_first() is not None:
  



这是一个简单的 Scrapy 爬虫示例代码,用于爬取读书网站 (https://www.dushu.com/) 上的书籍信息。代码中定义了一个名为 ScuwItem 的 Item 类,用于存储爬取到的书籍信息。以下是代码的详细说明: 1. 导入 Scrapy 和 ScuwItem 类: ```python import scrapy from scuw.items import ScuwItem ``` 2. 定义名为 DushuSpider 的 Spider 类: ```python class DushuSpider(scrapy.Spider): name = "dushu" allowed_domains = ["www.dushu.com"] start_urls = ["https://www.dushu.com/lianzai/"] ``` 这里定义了 Spider 的名称 (name)、允许爬取的域名 (allowed_domains) 和起始 URL (start_urls)。在这个示例中,Spider 将从 https://www.dushu.com/lianzai/ 开始爬取。 3. 定义 parse 方法: ```python def parse(self, response): print('=================') li_list = response.xpath('//div[@class="bookslist"]//div[@class="book-info"]') for li in li_list: name = li.xpath('.//a/text()').extract_first() href = li.xpath('.//a/@href').extract_first() url = "https://www.dushu.com"+href yield scrapy.Request(url=url, callback=self.response_second, meta={'name': name}) ``` 在这个方法中,首先打印了一条分隔线,然后使用 XPath 选择器找到了页面中所有书籍的信息。对于每个书籍,我们提取了书名和链接,并使用 yield 语句返回一个新的 Request 对象,以便在 response_second 方法中处理。这里我们还使用 meta 参数将书名传递给 response_second 方法。 4. 定义 response_second 方法: ```python def response_second(self, response): src = response.xpath('//div[@class="bookdetails-left"]//div[@class="pic"]/img/@src').extract_first() name = response.meta['name'] data = ScuwItem(src=src, name=name) yield data ``` 在这个方法中,我们使用 XPath 选择器找到了书籍详情页面中的书籍封面图片链接,并从 meta 中提取了书名。接着,我们创建了一个 ScuwItem 对象,并使用 yield 语句将其输出。 5. 在 settings.py 文件中启用 Item Pipeline: ```python ITEM_PIPELINES = { 'scuw.pipelines.ScuwPipeline': 300, } ``` 这个示例中,我们将数据存储到了数据库中,因此我们需要启用相应的 Item Pipeline。 6. 运行爬虫: ```bash scrapy crawl dushu ``` 以上就是这个爬虫示例的详细说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值