【发布时间】:2021-10-23 23:21:35
【问题描述】:
我创建了一个爬虫来从以下 URL 中提取数据“https://olympics.com/tokyo-2020/olympic-games/en/results/cycling-road/athlete-profile-n1346266-aalerud-katrine. htm”,但我无法在“rank”列中提取数据。我使用 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
}
非常感谢您
【问题讨论】:
标签: python xpath scrapy css-selectors