首页 > 解决方案 > 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
        }

非常感谢您提前

标签: pythonxpathscrapycss-selectors

解决方案


获取排名值的 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())                    

推荐阅读