如何通过XPath将相对URL转换为完整绝对URL?
解决Scrapy中相对URL转绝对URL的方法
这里给你两种Scrapy原生支持的靠谱方案,直接修改代码就能解决问题:
方法1:用response.urljoin()生成绝对URL
这个方法会自动基于当前页面的URL(response.url)拼接相对路径,不用手动拼接域名。修改你的parse方法如下:
import scrapy class AtasehirSpider(scrapy.Spider): name = 'atasehir' allowed_domains = ['www.sahibinden.com'] start_urls = ['https://www.sahibinden.com/satilik/istanbul-atasehir?address_region=2'] def parse(self, response): for ad_href in response.xpath("//td[@class='searchResultsLargeThumbnail']/a/@href"): # 将相对URL转换为绝对URL absolute_url = response.urljoin(ad_href.get()) print(absolute_url) # 如果需要爬取内页,用绝对URL生成请求 yield scrapy.Request(url=absolute_url, callback=self.parse_ad_detail) # 内页信息解析函数示例 def parse_ad_detail(self, response): # 在这里编写提取房源内页信息的逻辑,比如: title = response.xpath("//h1[@class='classifiedDetailTitle']/text()").get() price = response.xpath("//div[@class='classifiedInfo']//span[@class='price']/text()").get() yield { 'title': title, 'price': price }
方法2:用response.follow()直接处理相对URL
response.follow()是Scrapy推荐的请求生成方式,它原生支持相对路径,内部会自动完成相对URL到绝对URL的转换,写法更简洁:
import scrapy class AtasehirSpider(scrapy.Spider): name = 'atasehir' allowed_domains = ['www.sahibinden.com'] start_urls = ['https://www.sahibinden.com/satilik/istanbul-atasehir?address_region=2'] def parse(self, response): # 直接遍历a标签选择器,response.follow会自动提取href并转成绝对URL for ad in response.xpath("//td[@class='searchResultsLargeThumbnail']/a"): yield response.follow(ad, callback=self.parse_ad_detail) # 也可以直接传入相对路径字符串: # for ad_href in response.xpath("//td[@class='searchResultsLargeThumbnail']/a/@href"): # yield response.follow(ad_href.get(), callback=self.parse_ad_detail) def parse_ad_detail(self, response): # 内页信息提取逻辑示例 title = response.xpath("//h1[@class='classifiedDetailTitle']/text()").get() price = response.xpath("//div[@class='classifiedInfo']//span[@class='price']/text()").get() yield { 'title': title, 'price': price }
如果之前尝试这两种方法没成功,大概率是调用方式有误——比如使用urljoin时没传入正确的相对路径字符串,或者用follow时传错了参数。上面的代码可以直接替换你原有的parse方法,运行后就能看到绝对URL输出,或者正常发起内页请求。
内容的提问来源于stack exchange,提问作者6wom9
相关产品推荐
相关产品推荐

