【问题标题】:Scrapy: Do not crawl links on other domains pageScrapy:不要抓取其他域页面上的链接
【发布时间】:2016-06-16 11:15:40
【问题描述】:

下面是我为获取 NecToday.com 上的所有链接而创建的蜘蛛。

import socket
import scrapy

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector

class PropertiesItem(scrapy.Item):
    # Primary fields
    title = scrapy.Field()
    url = scrapy.Field()

class NecSpider(CrawlSpider):
    name = "NecSpider"
    #allowed_domains = ["nectoday.com"]
    start_urls = ["http://nectoday.com"]

    rules = (
        Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('//a',)), callback="parse_items", follow= True),
    )

    def parse_items(self, response):
        hxs = HtmlXPathSelector(response)
        print(response.url)
        item = PropertiesItem()
        item["title"] = response.xpath("//title/text()").extract()
        item["url"] = response.url
        return(item)

此代码开始获取网站上存在的所有链接。有些页面也有 YouTube 链接。问题是,一旦第一个 YouTube 链接被抓取,它就会开始抓取从第一个 YouTube 链接引用的其他 YouTube 链接。

我想抓取第一个 YouTube 链接,但没有其他链接。 YouTube 只是一个例子。明天也可以是另一个站点。如何实现?

【问题讨论】:

  • 您可以创建一个规则来匹配所有 youtube 链接而不需要关注。
  • 它只适用于 YouTube / 已知主机。我想要所有其他域链接而不关注。如果你能提供示例代码对我来说会很棒。

标签: python python-2.7 scrapy scrapy-spider


【解决方案1】:

为什么不尝试一些类似的东西:

start_urls=["http://nectoday.com"] 

def parse(self, response):
    #parse whatever you need

    for url in response.selector.xpath('//@href').extract():
        if 'youtube.com' in url:
            yield scrapy.Request(url, callback=self.parse_no_follow)
        else:
            yield scrapy.Request(url, callback=self.parse)

def parse_no_follow(self, response):
    #parse whatever you want and not follow anymore links

【讨论】:

    【解决方案2】:

    这只会从您允许的域中抓取。

    class QuotesSpider(CrawlSpider):
        name = "your app name"
        n=0
    
        allowed_domains = ['domain']
        start_urls=['anywebpage']
        rules = (
            Rule(LinkExtractor(), callback='parse_item', follow=True),
        )
    
        def parse_item(self, response):
            QuotesSpider.n=QuotesSpider.n+1
            if (len(response.body)>100):
    
                h = html2text.HTML2Text()
                h.ignore_links = True
                h.ignore_images = True
                h.body_width = 0
                dd = response.body.decode("utf-8")
                init=dd.find("<p>")
            while init>0:
                end = dd.find("</p>", init)
                if end>0:
                    o=h.handle(dd[init:end+4]+"\n")
                    supersentences=o.split('\n')
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多