使用scrapy递归地爬网站点

Mac*_*cro 6 python scrapy web-scraping

我正在尝试使用scrapy废弃网站.

这是我到目前为止基于http://thuongnh.com/building-a-web-crawler-with-scrapy/编写的代码 (原始代码根本不起作用所以我试图重建它)

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders             import Spider
from scrapy.selector         import HtmlXPathSelector
from nettuts.items            import NettutsItem
from scrapy.http            import Request
from scrapy.linkextractors import LinkExtractor


class MySpider(Spider):
    name = "nettuts"
    allowed_domains = ["net.tutsplus.com"]
    start_urls = ["http://code.tutsplus.com/posts?"]
    rules = [Rule(LinkExtractor(allow = ('')), callback = 'parse', follow = True)]

    def parse(self, response):
        hxs  = HtmlXPathSelector(response)
        item = []

        titles    = hxs.xpath('//li[@class="posts__post"]/a/text()').extract()
        for title in titles:
            item             = NettutsItem()
            item["title"]     = title
            yield item
        return
Run Code Online (Sandbox Code Playgroud)

问题是抓取工具进入起始页面但在此之后不会废弃任何页面.

小智 10

以下是一个好主意:

"使用scrapy递归爬网"可能有两个用例.

一个).我们只想使用表格的分页按钮和获取数据来浏览网站.这是相对简单的.

class TrainSpider(scrapy.Spider):
    name = "trip"
    start_urls = ['somewebsite']
    def parse(self, response):
        ''' do something with this parser '''
        next_page = response.xpath("//a[@class='next_page']/@href").extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)`
Run Code Online (Sandbox Code Playgroud)

观察最后4行.这里

  1. 我们从"下一步"分页按钮获取下一页链接表格下一页xpath.
  2. if条件检查,如果它不是分页的结束.
  3. 使用urljoin加入主链接的此链接(我们在步骤1中获得)
  4. 对'parse'回调方法的递归调用.

B)我们不仅要跨页面移动,还要从该页面中的一个或多个链接中提取数据.

class StationDetailSpider(CrawlSpider):
    name = 'train'
    start_urls = [someOtherWebsite]
    rules = (
        Rule(LinkExtractor(restrict_xpaths="//a[@class='next_page']"), follow=True),
        Rule(LinkExtractor(allow=r"/trains/\d+$"), callback='parse_trains')
    )
    def parse_trains(self, response):
        '''do your parsing here'''
Run Code Online (Sandbox Code Playgroud)

在这里,观察:

  1. 我们正在使用'scrapy.Spider'父类的'CrawlSpider'子类

  2. 我们设置为'规则'

    a)第一条规则只检查是否有"next_page"可用并跟随它.

    b)第二个规则请求页面上所有格式的链接,例如'/ trains/12343',然后调用'parse_trains'来执行和解析操作.

  3. 重要提示:请注意,由于我们使用的是"CrawlSpider"子类,因此我们不希望在此处使用常规的"parse"方法.这个类还有一个'parse'方法,所以我们不想覆盖它.请记住将您的回拨方法命名为"解析"以外的其他方法.


ale*_*cxe 5

问题是Spider您使用什么类作为基础。scrapy.Spider是一个简单的蜘蛛不支持的规则和链接提取

而是使用CrawlSpider

class MySpider(CrawlSpider):
Run Code Online (Sandbox Code Playgroud)