Python中scrapy的CrawlSpider爬取全站时,遇到干扰怎么破?
比如我要爬取的网站是 https://xxx.com,在 log 信息中看到得到的网页有很多 https://xxx.com?mdtp=30&p=8+++++++++++++++++++ 而且+号是不断的增加的,网站返回的是同一个页面。使用 linkExtractor 去过滤吗?
Python中scrapy的CrawlSpider爬取全站时,遇到干扰怎么破?
9 回复
把它处理掉
核心思路: 在 CrawlSpider 的 rules 中,通过 LinkExtractor 的 deny 参数或自定义 process_links 方法过滤干扰链接。
具体做法:
-
使用
deny参数(正则匹配排除):在LinkExtractor中直接定义拒绝规则,排除匹配特定模式的URL(如广告、评论分页、社交媒体分享链接等)。import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class MySpider(CrawlSpider): name = 'example' allowed_domains = ['example.com'] start_urls = ['http://www.example.com'] rules = ( Rule(LinkExtractor(deny=(r'/ads/', r'/comment/', r'\.php\?', r'share\.php')), callback='parse_item', follow=True), ) def parse_item(self, response): # 你的解析逻辑 yield {'url': response.url} -
使用
process_links方法(自定义过滤逻辑):在Rule中定义process_links函数,对提取到的链接列表进行更复杂的过滤(如根据链接文本、属性等)。class MySpider(CrawlSpider): name = 'example' allowed_domains = ['example.com'] start_urls = ['http://www.example.com'] rules = ( Rule(LinkExtractor(), callback='parse_item', follow=True, process_links='filter_links'), ) def parse_item(self, response): yield {'url': response.url} def filter_links(self, links): # 过滤掉链接文本包含“广告”或URL中包含“utm_source”的链接 return [link for link in links if '广告' not in link.text and 'utm_source' not in link.url]
总结建议: 优先用 deny 做简单模式排除,复杂逻辑用 process_links 处理。
这说明人家并不想让你爬
啥网站啊,这么溜,这个反爬虫机制真 low
高校的,哈哈
用正则过滤链接吧,很好解决。
又见 xxx.com …
上班打开 xxx.com,旁边连个妹子,让我情以何堪


