python - Scrapy:不要抓取其他域页面上的链接

标签 python python-2.7 scrapy

下面是我创建的蜘蛛,用于获取 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 只是一个例子。明天也可能是另一个站点。如何实现这一目标?

最佳答案

为什么不尝试一下这样的事情:

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

关于python - Scrapy:不要抓取其他域页面上的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857554/

相关文章:

python - 根据文件设置vim python缩进空间

Python在函数中使用 "global"返回新变量

python - 使用字符串模板时如何将所有循环元素追加到单行中?

python - Scrapy Authenticated Spider 获取内部服务器错误

python - Scrapy - 关注 RSS 链接

python - 通过修改原始列表就地重新排列列表,将偶数索引值放在前面

python - 如何使用 BeautifulSoup 和 Python 仅从相似元素中提取某些文本

Python sleep() 禁止用逗号打印?

python - 如何乘以列表列表的位置

python - 如何在Ubuntu 16.04上安装Scrapy?