首页 > 解决方案 > 构建 URL 列表时 Scrapy 错误无效的 xPath 表达式

问题描述

我正在用 Scrapy 搜索 apartments.com。apartments.com/boston-ma/X我想以X 是表示页码的整数的形式转到每一页。

在那里,我想提取所有属性 URL,它们都具有property-link. 然后我将为每个属性编写一个 parse_item。

我收到错误

ValueError: XPath 错误: //*[contains(@class, 'property-link'')]/@href 中的表达式无效

我不知道我的 xPath 出了什么问题。请指教。

代码:

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from apt.items import AptItem
from urllib.parse import urljoin

class AptSpider(CrawlSpider):
    name = "apt"
    allowed_domains = ["apartments.com"]
    start_urls = ["https://www.apartments.com/boston-ma/"]

    rules = (Rule(LinkExtractor(allow=r'[1-9]+/*'), callback='parse_urls', follow=True),)

    def parse_urls(self, response):
        apts = response.xpath("//*[contains(@class, 'property-link'')]/@href").extract()
        for a in apts:
            url = urljoin(response.url, a)
            yield scrapy.Request(url, callback=parse_item)


    #def parse_item(self, response):
        #scrape data here
        #item = AptItem()

谢谢!

标签: pythonxpathscrapy

解决方案


你写 apts = response.xpath("//*[contains(@class, 'property-link'')]/@href").extract() 你必须写 apts = response.xpath("//*[contains(@class, 'property-link')]/@href").extract() 你正在添加'property-link''两个引号。属性链接后


推荐阅读