python - 构建 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()
谢谢!
解决方案
你写
apts = response.xpath("//*[contains(@class, 'property-link'')]/@href").extract()
你必须写
apts = response.xpath("//*[contains(@class, 'property-link')]/@href").extract()
你正在添加'property-link''两个引号。属性链接后
推荐阅读
- react-native - 按下时内部的 TouchableOpacity 矩形
- python - 无法使用 python 从 JSON 生成正确的 csv 文件
- python - 如何计算具有 2 个字符串元组的列表中的第一个元素?
- tomcat9 - 使用cmd运行tomcat服务器的问题
- quarkus - 是否可以在自定义扩展中使用 Qute 模板?
- python - 正则表达式:准确输入 4 位数字,检查输入的数字是否出现在前 10,000 个字符中
- json - 来自 Spring REST API 端点的文本响应,如何在 Angular 前端检索它
- python - 在 python 中使用 su 的多个命令 - 用户
- python - 如何记录 tensorflow 对象检测 api 的训练和结果?
- visual-studio-code - VS 代码扩展在编辑其 JS 后不反映更改