【问题标题】:How to crawl links on all pages of a web site with Scrapy如何使用 Scrapy 抓取网站所有页面上的链接
【发布时间】:2015-06-01 18:49:27
【问题描述】:

我正在学习scrapy,我正在尝试提取所有包含:“http://lattes.cnpq.br/andasequenceofnumbers”的链接,例如:http://lattes.cnpq.br/0281123427918302 但我不知道网站上包含这些信息的页面是什么。 例如这个网站:

http://www.ppgcc.ufv.br/

我想要的链接在这个页面上:

http://www.ppgcc.ufv.br/?page_id=697

我能做什么? 我正在尝试使用规则,但我不知道如何正确使用正则表达式。 谢谢

1 编辑----

我需要在主 (ppgcc.ufv.br) 站点的所有页面上搜索链接类型 (http://lattes.cnpq.br/asequenceofnumber)。我的目标是获取所有链接 lattes.cnpq.br/numbers 但我不知道它们在哪里。我使用的是一个简单的代码,实际上是这样的:

class ExampleSpider(scrapy.Spider):
    name = "example"
    allowed_domains = ["ppgcc.ufv.br"]
    start_urls = (
        'http://www.ppgcc.ufv.br/',
    )
    rules = [Rule(SgmlLinkExtractor(allow=[r'.*']), follow=True),
             Rule(SgmlLinkExtractor(allow=[r'@href']), callback='parse')]

    def parse(self, response):
        filename = str(random.randint(1, 9999))
        open(filename, 'wb').write(response.body)

#I'm trying to understand how to use rules correctly

2 编辑----

使用:

class ExampleSpider(CrawlSpider):
    name = "example"
    allowed_domains = [".ppgcc.ufv.br"]
    start_urls = (
        'http://www.ppgcc.ufv.br/',
    )
    rules = [Rule(SgmlLinkExtractor(allow=[r'.*']), follow=True),
            Rule(SgmlLinkExtractor(allow=[r'@href']), callback='parse_links')]
    def parse_links(self, response):
        filename = "Lattes.txt"
        arquivo = open(filename, 'wb')
        extractor = LinkExtractor(allow=r'lattes\.cnpq\.br/\d+')
        for link in extractor.extract_links(response):
            url = link.urlextractor = LinkExtractor(allow=r'lattes\.cnpq\.br/\d+')
            arquivo.writelines("%s\n" % url)                
            print url

它告诉我:

C:\Python27\Scripts\tutorial3>scrapy crawl example
2015-06-02 08:08:18-0300 [scrapy] INFO: Scrapy 0.24.6 started (bot: tutorial3)
2015-06-02 08:08:18-0300 [scrapy] INFO: Optional features available: ssl, http11
2015-06-02 08:08:18-0300 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tutorial3.spiders', 'SPIDER_MODULES': ['tutorial3
.spiders'], 'BOT_NAME': 'tutorial3'}
2015-06-02 08:08:19-0300 [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState

2015-06-02 08:08:19-0300 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMidd
leware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMidd
leware, ChunkedTransferMiddleware, DownloaderStats
2015-06-02 08:08:19-0300 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLe
ngthMiddleware, DepthMiddleware
2015-06-02 08:08:19-0300 [scrapy] INFO: Enabled item pipelines:
2015-06-02 08:08:19-0300 [example] INFO: Spider opened
2015-06-02 08:08:19-0300 [example] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-06-02 08:08:19-0300 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-06-02 08:08:19-0300 [scrapy] DEBUG: Web service listening on 127.0.0.1:6080
2015-06-02 08:08:19-0300 [example] DEBUG: Crawled (200) <GET http://www.ppgcc.ufv.br/> (referer: None)
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.cgu.gov.br': <GET http://www.cgu.gov.br/acessoainformacao
gov/>
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.brasil.gov.br': <GET http://www.brasil.gov.br/>
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.ppgcc.ufv.br': <GET http://www.ppgcc.ufv.br/>
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.ufv.br': <GET http://www.ufv.br/>
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.dpi.ufv.br': <GET http://www.dpi.ufv.br/>
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.portal.ufv.br': <GET http://www.portal.ufv.br/?page_id=84
>
2015-06-02 08:08:19-0300 [example] DEBUG: Filtered offsite request to 'www.wordpress.org': <GET http://www.wordpress.org/>
2015-06-02 08:08:19-0300 [example] INFO: Closing spider (finished)
2015-06-02 08:08:19-0300 [example] INFO: Dumping Scrapy stats:
        {'downloader/request_bytes': 215,
         'downloader/request_count': 1,
         'downloader/request_method_count/GET': 1,
         'downloader/response_bytes': 18296,
         'downloader/response_count': 1,
         'downloader/response_status_count/200': 1,
         'finish_reason': 'finished',
         'finish_time': datetime.datetime(2015, 6, 2, 11, 8, 19, 912000),
         'log_count/DEBUG': 10,
         'log_count/INFO': 7,
         'offsite/domains': 7,
         'offsite/filtered': 42,
         'request_depth_max': 1,
         'response_received_count': 1,
         'scheduler/dequeued': 1,
         'scheduler/dequeued/memory': 1,
         'scheduler/enqueued': 1,
         'scheduler/enqueued/memory': 1,
         'start_time': datetime.datetime(2015, 6, 2, 11, 8, 19, 528000)}
2015-06-02 08:08:19-0300 [example] INFO: Spider closed (finished)

我在看网站的源代码,有更多的页面链接没有抓取到,可能是我的规则不正确

【问题讨论】:

  • 您想提取这些链接还是要关注这些链接?根据您的需要,您需要以不同的方式处理它。
  • 另外,如果你知道你想要的所有链接都在页面http://www.ppgcc.ufv.br/?page_id=697中,你可以在start_urls中使用它。
  • 如果您粘贴代码,我们可以更轻松地为您提供帮助。
  • colega vi que vcé br, então fica mais facil de nos comunicarmos....您是否重复待办事项 o processo para varios sites entende? Sites de universidades que nao possuem o mesmo padrao, entao minha ideia era pegar todos os links lattes.cnpq.br/numeros que eu encontrar dentro de qualquer pagina do site
  • 喂,布鲁诺! :) 听着,这里用葡萄牙语写不太礼貌(内容应该对其他人也有帮助)。您可以在 Stackoverflow em Português 中用葡萄牙语提问:pt.stackoverflow.com/tags/scrapy

标签: web web-crawler scrapy extract


【解决方案1】:

所以,首先有几件事:

1) rules 属性仅在您扩展 CrawlSpider 类时有效,如果您扩展更简单的 scrapy.Spider,它们将不起作用。

2) 如果你走rules 和CrawlSpider 路由,你不应该覆盖默认的parse 回调,因为默认实现是实际调用规则的东西——所以你想为你的回调。

3) 要实际提取您想要的链接,您可以在回调中使用LinkExtractor 从页面中抓取链接:

from scrapy.contrib.linkextractors import LinkExtractor

class MySpider(scrapy.Spider):
    ...

    def parse_links(self, response):
        extractor = LinkExtractor(allow=r'lattes\.cnpq\.br/\d+')
        for link in extractor.extract_links(response):
            item = LattesItem()
            item['url'] = link.url

希望对你有帮助。

【讨论】:

  • 我很接近了,但再看版本,可能我的规则不正确
  • @BrunoCarazato 我相信你只需要一条规则就可以了:Rule(SgmlLinkExtractor(allow=[r'.*']), callback='parse_links', follow=True)
  • @BrunoCarazato 这告诉 Scrapy:“只需跟踪域中的每个链接,为其调用 parse_links 并继续对每个页面应用此规则”
  • 它的作品很棒!谢谢!编辑-输出提供了我需要的所有链接,但一两个是这样的=“saudecoeste.ufms.br/%20http://lattes.cnpq.br/4903660157313116”而不仅仅是“lattes.cnpq.br/4903660157313116”
  • @BrunoCarazato 这看起来像是 HTML 页面中的问题。也许链接href=" http...."中有一个空格?我想你必须为这种情况做一些后期处理。
猜你喜欢
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 2018-01-09
相关资源
最近更新 更多