python - Scrapy爬虫返回重复值
问题描述
下面是我的完整代码。我不知道为什么它会返回很多重复项。请问有什么办法吗?我正在尝试从此链接“ https://www.compass.com/agents ”请求所有区域并提取代理的信息。
# -*- coding: utf-8 -*-
import scrapy
class MainSpider(scrapy.Spider):
name = 'main'
start_urls = ["https://www.compass.com/agents"]
def parse(self, response):
regions = response.xpath('//ul[@class="geoLinks-list textIntent-caption1--strong"]/li')
for each in regions:
region_link = each.xpath('.//a/@href').get()
region_name = each.xpath('.//a/text()').get()
yield response.follow(url=region_link, callback=self.parse_data, meta={"region_text": region_name})
def parse_data(self, response):
region = response.request.meta["region_text"]
agents = response.xpath('//div[@class="agentCard-contact"]')
for agent in agents:
name = agent.xpath('normalize-space(//div[@class="agentCard-contact"]/a/text())').get()
profile_link = agent.xpath('//div[@class="agentCard-contact"]/a/@href').get()
email = agent.xpath('//a[@class="textIntent-body agentCard-email"]/@href').get()
mobile = agent.xpath('//a[@class="textIntent-body agentCard-phone"]/@href').get()
yield {
"Name": name,
"Profile_link": profile_link,
"Email": email,
"Mobile": mobile,
"Region": region,
}
解决方案
我觉得你的xpath有问题。使用以下内容更改您的 xpath 并尝试:
name = agent.xpath('normalize-space(.//a[@class="textIntent-headline1 agentCard-name"]/text())').get()
profile_link = agent.xpath('.//a[@class="textIntent-headline1 agentCard-name"]/@href').get()
email = agent.xpath('.//a[@class="textIntent-body agentCard-email"]/@href').get()
mobile = agent.xpath('.//a[@class="textIntent-body agentCard-phone"]/@href').get()
推荐阅读
- hibernate - 从 IntelliJ idea 运行时未填充 Hibernate 集合
- groovy - groovy中的字符串插值
- sql - BigQuery 中不区分大小写的 LIKE
- python - Browsermob-Proxy - 通过 SSL 读取 XHR 的问题
- mysql - 删除带有感叹号和反引号的数据库
- json - 向模型添加新属性:转换现有 JSON
- react-native - 如何使用 Android Studio 查看 React Native 代码的变化
- python - 使用附加到列表的 for 循环进行多处理
- python - 我从命令行执行将参数传递给 URL,但由于连接无效而引发错误
- java - 无法使用 SMSmanager Android 将通话记录作为消息发送