【问题标题】:Scrapy - Exclude Unwanted URLs (Like Comments)Scrapy - 排除不需要的 URL(喜欢评论)
【发布时间】:2013-05-26 16:45:45
【问题描述】:

我正在使用 Scrapy 抓取网站以获取所有页面,但我当前的代码规则仍然允许我获取不需要的 URL,例如除了帖子的主 URL 之外的“http://www.example.com/some-article/comment-page-1”之类的评论链接。我可以在规则中添加什么来排除这些不需要的项目?这是我当前的代码:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.item import Item

class MySpider(CrawlSpider):
    name = 'crawltest'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']
    rules = [Rule(SgmlLinkExtractor(allow=[r'/\d+']), follow=True), Rule(SgmlLinkExtractor(allow=[r'\d+']), callback='parse_item')]

    def parse_item(self, response):
        #do something

【问题讨论】:

    标签: python web-crawler scrapy


    【解决方案1】:

    SgmlLinkExtractor 有一个名为deny 的可选参数,这将仅在允许正则表达式为真且拒绝正则表达式为假时匹配规则

    来自docs的示例:

    rules = (
            # Extract links matching 'category.php' (but not matching 'subsection.php')
            # and follow links from them (since no callback means follow=True by default).
            Rule(SgmlLinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
    
            # Extract links matching 'item.php' and parse them with the spider's method parse_item
            Rule(SgmlLinkExtractor(allow=('item\.php', )), callback='parse_item'),
        )
    

    也许您可以检查该网址是否不包含单词comment

    【讨论】:

    • 这行得通。但是如何使用正则表达式来达到同样的效果呢?例如,约束 no / 跟随 some-article 以使 http://www.example.com/some-article/comment-page-1 无效。我试过allow=r"some-article[^/]?",但没有用。有什么想法吗?
    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 2016-03-24
    • 2013-11-05
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多