Python中CrawlSpider爬取全网站时信息不全,如何解决相对链接未转绝对链接的问题?

您好,我把我的问题给你详细描述一下,请您帮我解决一下。
用的是 crawlspider 爬取乐融商城全部的网站源代码,但是爬取到精选配件页面(全部分类选项里面)时,由于商品(“比如:乐视蓝牙耳机”)的链接只是相对的,结果导致无法爬取商品页面源代码
Python中CrawlSpider爬取全网站时信息不全,如何解决相对链接未转绝对链接的问题?

2 回复

用CrawlSpider爬全站时,相对链接没转绝对链接确实是个常见坑。核心问题是LinkExtractor提取到的链接是相对路径,但Scrapy默认的请求处理逻辑里,response.follow()方法能自动处理相对链接,而直接用scrapy.Request()构造请求时不会。

最直接的解决方案是在你的parse_item回调方法里,用response.follow()来发起后续请求,而不是scrapy.Request()。这个方法会自动使用当前响应的URL作为基准,将相对链接补全为绝对链接。

给你个代码示例,重点看parse_item方法里的写法:

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(), callback='parse_item', follow=True),
    )
    
    def parse_item(self, response):
        # 假设我们要提取页面里的某个链接继续爬
        # 错误做法:直接用scrapy.Request()
        # next_url = response.css('a.next-page::attr(href)').get()
        # yield scrapy.Request(next_url, callback=self.parse_item)
        
        # 正确做法:用response.follow()
        next_page = response.css('a.next-page::attr(href)').get()
        if next_page:
            yield response.follow(next_page, callback=self.parse_item)
        
        # 你的数据提取逻辑
        item = {
            'url': response.url,
            'title': response.css('title::text').get(),
            # ... 其他字段
        }
        yield item

如果你非要用scrapy.Request(),那就得手动处理URL拼接:

from urllib.parse import urljoin

next_url = response.css('a.next-page::attr(href)').get()
if next_url:
    absolute_url = urljoin(response.url, next_url)
    yield scrapy.Request(absolute_url, callback=self.parse_item)

但说实话,用response.follow()更简洁,它内部就是调用的urljoin,还处理了其他细节。

总结:用response.follow()替代scrapy.Request()来处理提取到的链接。


scrapy 框架的话有个方法 response.urljoin(你提取出来的链接) 可以补全

回到顶部