Scrapy CrawlSpider 什么都不爬

Scrapy CrawlSpider Crawls Nothing

我正在尝试抓取 Booking.Com。蜘蛛打开和关闭而不打开和爬行 url。[输出][1] [1]: https://i.stack.imgur.com/9hDt6.png 我是 python 和 Scrapy 的新手。这是我到目前为止编写的代码。请指出我做错了什么。

import scrapy
import urllib
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.item import Item
from scrapy.loader import ItemLoader
from CinemaScraper.items import CinemascraperItem


class trip(CrawlSpider):
 name="tripadvisor"

def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/page/1/',
            'http://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)


def parse(self, response):
        reviewsurl = response.xpath('//a[@class="show_all_reviews_btn"]/@href')
        url = response.urljoin(reviewsurl[0].extract())
        self.pageNumber = 1
        return scrapy.Request(url, callback=self.parse_reviews)


def parse_reviews(self, response):
     for rev in response.xpath('//li[starts-with(@class,"review_item")]'):
            item =CinemascraperItem()
            #sometimes the title is empty because of some reason, not sure when it happens but this works
            title = rev.xpath('.//*[@class="review_item_header_content"]/span[@itemprop="name"]/text()')
            if title:
                item['title'] = title[0].extract()
                positive_content = rev.xpath('.//p[@class="review_pos"]//span/text()')
                if positive_content:
                    item['positive_content'] = positive_content[0].extract()
                negative_content = rev.xpath('.//p[@class="review_neg"]/span/text()')
                if negative_content:
                    item['negative_content'] = negative_content[0].extract()
                item['score'] = rev.xpath('./*[@class="review_item_header_score_container"]/span')[0].extract()
                #tags are separated by ;
                item['tags'] = ";".join(rev.xpath('.//ul[@class="review_item_info_tags/text()').extract())
                yield item

     next_page = response.xpath('//a[@id="review_next_page_link"]/@href')
     if next_page:
      url = response.urljoin(next_page[0].extract())
      yield scrapy.Request(url, self.parse_reviews)

您正在覆盖 CrawlSpider subclass 上的 parse 方法,根据 documentation 不推荐这样做:

When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses the parse method itself to implement its logic. So if you override the parse method, the crawl spider will no longer work.

不过,我在您的 Spider 中没有看到规则,所以我建议您只切换到 scrapy.spiders.Spider 而不是 scrapy.spiders.CrawlSpider。再次从 Spider class 和 运行 继承它,它应该如您所愿地工作。

我想指出的是,在你的问题中你提到了一个网站 booking.com 但在你的蜘蛛中你有 link 到该网站的网站是 scrapy 教程的官方文件...为了解释,将继续使用报价网站....

好的,我们开始...所以在您的代码片段中您使用了爬​​行蜘蛛,其中值得一提的是解析函数已经是爬行蜘蛛背后逻辑的一部分。就像我之前提到的,通过将你的解析重命名为不同的名称,例如 parse_item 这是你创建滚动蜘蛛时默认的初始函数,但实际上你可以随意命名。通过这样做,我相信我实际上应该抓取该网站,但这完全取决于您的代码是否正确。

简而言之,通用蜘蛛和爬行蜘蛛之间的区别在于,在使用爬行蜘蛛时,您使用诸如 link 提取器和规则之类的模块,其中设置了某些参数,以便在开始时 URL 遵循用于在页面中导航的模式,使用各种有用的参数来做到这一点......其中最后一个规则集是你将汽车返回的规则集。 iIn 换句话说...爬网蜘蛛创建请求导航的逻辑。

请注意,在规则集中....我输入...“/page.”....使用“.”是一个正则表达式,表示... .. "From the page im in... anyt links on this page that follow the pattern ..../page" 它将跟随并回调到 parse_item..."

这是一个超级简单的示例...因为您可以输入模式以仅跟随或仅回调您的项目解析功能...

对于普通蜘蛛,您必须手动锻炼网站导航才能获得您想要的内容...


CrawlSpider

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from quotes.items import QuotesItem

class QcrawlSpider(CrawlSpider):
    name = 'qCrawl'
    allowed_domains = ['quotes.toscrape.com']
    start_urls = ['http://quotes.toscrape.com/']

    rules = (
        Rule(LinkExtractor(allow=r'page/.*'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        item = QuotesItem()
        item['quote'] =response.css('span.text::text').extract()
        item['author'] = response.css('small.author::text').extract()
        yield item

通用蜘蛛

import scrapy
from quotes.items import QuotesItem

class QspiSpider(scrapy.Spider):
    name = "qSpi"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ['http://quotes.toscrape.com']

    def parse(self, response):
        for quote in response.css("div.quote"):
            item = QuotesItem()
            item['quote'] = quote.css('span.text::text').extract()
            item['author'] = quote.css('small.author::text').extract()
            item['tags'] = quote.css("div.tags > a.tag::text").extract()
            yield item

        for nextPage in response.css('li.next a::attr(href)').extract():
            yield scrapy.Request(response.urljoin(nextPage))

一个


编辑:应 OP

要求的附加信息

"...I cannot understand how to add arguments to the Rule parameters"

好吧...让我们看看官方文档只是为了重申爬行蜘蛛的定义...

所以爬行蜘蛛通过使用规则集创建了遵循 links 背后的逻辑......现在假设我想用爬行蜘蛛爬行 craigslist 仅用于出售家居用品....我希望你注意红色的东西....

第一个是显示当我在 craigslist 家居用品页面上时

所以我们收集到..."search/hsh..." 中的任何内容都将是家居用品列表的页面,从加载页面的第一页开始。

对于红色的大数字“2”...是为了表明当我们在实际发布的项目中...所有项目似乎都有“.../hsh/...”所以任何links inside the previs page that has this pattern I want to follow and scrape from there ...所以我的蜘蛛会是这样的...

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from craigListCrawl.items import CraiglistcrawlItem

class CcrawlexSpider(CrawlSpider):
    name = 'cCrawlEx'
    allowed_domains = ['columbia.craigslist.org']
    start_urls = ['https://columbia.craigslist.org/']

    rules = (
        Rule(LinkExtractor(allow=r'search/hsa.*'), follow=True),
        Rule(LinkExtractor(allow=r'hsh.*'), callback='parse_item'),
    )

    def parse_item(self, response):
        item = CraiglistcrawlItem()
        item['title'] = response.css('title::text').extract()
        item['description'] = response.xpath("//meta[@property='og:description']/@content").extract()
        item['followLink'] = response.xpath("//meta[@property='og:url']/@content").extract()
        yield item

我希望你把它想象成你从着陆页到你的内容页面所在的步骤......所以我们登陆了我们的页面 start_url...... tSo我们说过,House Hold Items 有规律,所以正如您看到的第一条规则...

Rule(LinkExtractor(allow=r'search/hsa.*'), follow=True)

这里说允许遵循正则表达式模式 "search/hsa." ...请记住“.”是一个正则表达式,它匹配 "search/hsa" 之后的任何内容至少案例。

所以逻辑继续,然后说任何具有模式 "hsh.*" 的 link 都将回调到我的 parse_item

如果你认为它是从一个页面到另一个页面的步骤 "clicks" 它应该有所帮助......虽然完全可以接受,但通用蜘蛛会给你最大的资源控制你的 scrapy 项目将最终使用这意味着一个写得好的蜘蛛应该更精确和更快。