【问题标题】:scrapy crawl urls retrieved检索到的抓取网址
【发布时间】:2018-09-23 11:06:23
【问题描述】:

我在scrapy中有这个蜘蛛的sn-p

# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from infoseeker.items import InfoseekerItem as InfoItem



class SeekerSpider(CrawlSpider):
    name = 'seeker'
    allowed_domains = ['info.mzalendo.com']
    start_urls = ['http://info.mzalendo.com/position/member-national-assembly/?page=1']
    main_url = 'http://info.mzalendo.com/position/member-national-assembly/'
    urls = []
    retrieving = False

    def parse(self, response):
        if not self.retrieving:
            selector_list = response.css('.position')

            for selector in selector_list:
                self.urls.append(selector.css('a::attr(href)').extract()[0])

            found = response.css('.next::attr(href)').extract()
            if found:
                next_page = self.main_url + found[0] #uses ?page=2, ?page=3 format so appended to main url to avoid issues
            else:
                next_page = None

            if next_page is not None:
                yield response.follow(next_page, self.parse)
            else:
                self.retrieving = True

        #should run once all urls have been found
        for url in self.urls:
            pass #get content for url to be parsed

由于我要查询的内容列在页面上,首先我查询了所有页面并检索了 url 列表并将它们存储在 self.urls 中,一旦此过程完成,我打算开始查询现在检索有用信息的网址。

不确定yield 是否适合使用。

【问题讨论】:

    标签: python scrapy


    【解决方案1】:

    您需要做的是回调。调用另一个函数来处理您尝试抓取的 url。

    CALLBACK (callable) – 将调用此请求的响应(一旦下载)作为其第一个参数的函数。有关更多信息,请参阅下面的将附加数据传递给回调函数。如果请求没有指定回调,则蜘蛛的 parse() 方法将是

    Here,像这样

    import .....
    
    class SeekerSpider(CrawlSpider):
    
    name = 'seeker'
    allowed_domains = ['info.mzalendo.com']
    start_urls = ['http://info.mzalendo.com/position/member-national-assembly/?page=1']
    main_url = 'http://info.mzalendo.com/position/member-national-assembly/'
    urls = []
    retrieving = False
    
    def parse(self, response):
        .......
        #  All the above code in between.
        .......
    
        #should run once all urls have been found
        for url in self.urls:
            #get content for url to be parsed. USE CALLBACK
            yield scrapy.Request(url, callback=self.parse_url)
    
    def parse_url(self, response):
        #Do whatever you want with the response of desired url.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-25
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多