python - Python:如何使用 xpath 或 css 选择器提取排名列数据?
问题描述
我创建了一个爬虫来从以下网址“https://olympics.com/tokyo-2020/olympic-games/en/results/cycling-road/athlete-profile-n1346266-aalerud-katrine.htm”中提取数据,但是我无法在“排名”列上提取数据。我使用 for 循环尝试获取数据,但总是得到“无”值,我不明白为什么。这是我的代码的一部分:
class OlympicSpider(scrapy.Spider):
name = 'ath_spider'
start_urls = [
"https://olympics.com/tokyo-2020/olympic-games/en/results/cycling-road/athlete-profile-n1346266-aalerud-katrine.htm"
]
custom_settings = {
'FEED_FORMAT':'json',
'FEED_URI': 'athletes_tokyo.json'
}
def parse(self, response):
event = response.css('td > a.eventTagLink::text').getall()
rank=[]
for x in range(1,len(event)+1):
rank.append(response.xpath(
'//main/div/div[1]/div[1]/div[2]/a[1]/div/table/tbody/tr[%s]/td[3]/text()' %x).get())
yield{
'name' : response.css('h1::text').get().strip(),
'noc' : response.css('div.playerTag::attr(country)').get(),
'team' : response.css('a.country::text').get(),
'sport' : response.css('div.container-fluid > div.row > a::text').get(),
'sex' : response.xpath('//div/div[1]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/div[1]/div[3]/text()').extract()[-1].strip(),
'age': response.xpath('//div/div[1]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/div[1]/div[2]/text()').extract()[-1].strip(),
'event':event,
'rank':rank
}
非常感谢您提前
解决方案
获取排名值的 XPath 是
//table[@class='table table-schedule']//td[3]/text()
使用您的特定代码,它可能类似于
for x in range(1,len(event)+1):
rank.append(response.xpath("(//table[@class='table table-schedule']//td[3])[" + str(x) + "]/text()").get())
推荐阅读
- flutter - 带有嵌套小部件的 Flutter 表单验证
- azure-active-directory - Sharepoint Online OAuth 2.0 新 O365 租户的无效令牌类型
- python - 如何在 selenium 中关闭 iframe
- php - Symfony Seralizer 不序列化 OneToOne 关系/Doctrin Proxy
- c++11 - 如何在 Ubuntu 上安装 C++11 编译器?
- laravel - 在 null 上调用成员函数 pro_events()
- vba - 使用 Access 在单击时使用列表框在表中追加多条记录
- refresh - 为什么我的与 openstack 集成的 Manageiq 没有刷新?
- c - 嵌入式应用程序的简单内存分配
- javascript - 如何确定 Javascript UTF-16 字符串的字节大小