Python Scrapy 自动抓取下一页内容

最近在学下Scrapy,抓取下一页的时候遇到了问题

import scrapy
from crawlAll.items import CrawlallItem

class ToutiaoEssayJokeSpider(scrapy.Spider):
    name = "duanzi"
    allowed_domains = ["http://duanziwang.com"]
    start_urls = ['http://duanziwang.com/category/duanzi/page/1']

    def parse(self, response):
        for sel in response.xpath("//article[@class='excerpt excerpt-nothumbnail']"):
            item = CrawlallItem()
            item['Title'] = sel.xpath("//header/h2/a/text()").extract_first()
            item['Text'] = sel.xpath("//p[@class='note']/text()").extract_first()
            item['Views'] = sel.xpath("//p[1]/span[@class='muted'][2]/text()").extract_first()
            item['Time'] = sel.xpath("//p[1]/span[@class='muted'][1]/text()").extract_first()
            yield item
        next_page = response.xpath("//ul/li[@class='next-page']/a/@href").extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

具体代码如上,我只能抓取第一页的12条内容,第二页的连接我用print的时候也能打印出来,说明连接是获取成功了,就是:

next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

这两句代码没有回过头去调用parse,不知道为什么?请大神帮忙看看,谢谢了。

阅读 20.3k
5 个回答

allowed_domains里面的域名不要加http前缀

你尝试注释掉

next_page = response.urljoin(next_page)

实际上网站上的 next_page 就已经是绝对链接,这句的作用是把相对链接变成绝对链接。
在你这个例子中其实是多余的,而且不知道是否会返回什么东西,可能是返回 None,导致最后的回调失败


补充内容:

Request 函数应该是这样 import..我第一次看漏了

from scrapy.http import Request

参见:
https://doc.scrapy.org/en/lat...

新手上路,请多包涵

yield Request(

            url=nextpage_url,
            callback=self.list_parse,
            dont_filter=True #添加这个试试
        )

补充一下,我刚发现题主用的是extract_first(),说明next_page获取的不是list,而是字符串,那我说的可能不对。

原答案:
不知道题主解决了这个问题没有,今天我参考其他解决办法,解决了这个问题
改成这样

    if next_page is not None:
        next_page = next_page[0]
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, callback=self.parse)

原因:
next_page = response.xpath("//ul/li[@class='next-page']/a/@href").extract_first()
这个next_page获取的是一个列表,需要将它提取为字符串:
next_page = next_page[0]

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