python - Scrapy - 排除不需要的 URL(喜欢评论)

标签 python web-crawler scrapy

我正在使用 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

最佳答案

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'),
    )

也许您可以检查 url 是否不包含单词 comment

关于python - Scrapy - 排除不需要的 URL(喜欢评论),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16761435/

相关文章:

python - 如何从一个链接生成已解析的项目以及同一项目列表中其他链接的其他已解析的项目

python - Scrapy 蜘蛛显示同一项目中另一个不相关的蜘蛛的错误

python - pandas - 使用 DateTimeIndex 切片 DataFrame 的 Pythonic 方法

python - 文本文件中的Scrapy start_urls

javascript - scrapy填写POST表单

scrapy - 如何使用scrapy爬虫蜘蛛在SgmlLinkExtractor的 "allow"规则中包含起始网址

java - 如何使用 HtmlUnit 显示所有 AJAX 请求

Python minimize_scalar 计算多项式最小值不正确

python - GitPython pull 后工作副本中没有任何内容出现

python - python 2.5 中的相对导入