我有兴趣从类似 this 的页面中选择一些数据.我写了下面的脚本来做到这一点。问题是我选择了4个部分(crucible、titan、hunter、warlock),但是不同页面的数据位置不一样。我不确定我选择不同部分的方法是否合适。
def parse_country(self, response):
hxs = scrapy.Selector(response)
crucibleSummary = hxs.xpath('//*[@id="site-body"]/div[5]/div/div/div[1]/div[4]/div[2]').xpath('.//text()').extract()
crucibleSummaryData = [e.replace(',', '').replace('%', '').replace('\n', '').replace('Top', '').
replace('#', '').replace('\r', '').replace('\n', '').strip()
for e in crucibleSummary]
crucibleSummaryData = filter(None, crucibleSummaryData)
titan = hxs.xpath('//*[@id="site-body"]/div[5]/div/div/div[2]/div[3]/div[2]').xpath('.//text()').extract()
titanData = [e.replace(',', '').replace('%', '').replace('\n', '').replace('Top', '').replace('#', '').
replace('\r', '').replace('\n', '').strip() for e in titan]
titanData = filter(None, titanData)
warlock = hxs.xpath('//*[@id="site-body"]/div[5]/div/div/div[2]/div[3]/div[3]').xpath('.//text()').extract()
warlockData = [e.replace(',', '').replace('%', '').replace('\n', '').replace('Top', '').replace('#', '').
replace('\r', '').replace('\n', '').strip() for e in warlock]
warlockData = filter(None, warlockData)
hunter = hxs.xpath('//*[@id="site-body"]/div[5]/div/div/div[2]/div[3]/div[1]').xpath('.//text()').extract()
hunterData = [e.replace(',', '').replace('%', '').replace('\n', '').replace('Top', '').replace('#', '').
replace('\r', '').replace('\n', '').strip() for e in hunter]
hunterData = filter(None, hunterData)
item = DestinytrackerProfilesItem()
data = crucibleSummaryData
item['DTRscore'] = [float(data[1]), float(data[2])]
....
请您参考如下方法:
您当前的 XPath 表达式非常脆弱并且不可读。
如果我们不依赖于父 div 元素的相对位置及其位置,而是使用 block 标题会怎么样 - 在 Crucible 的情况下,它可能是:
//h2[. = 'Crucible Summary']/following::div[@class='stats-stat-list']
对于术士和其他角色,您可以寻找包含子字符串的strong 元素文本:
//div[@class = "character-details" and contains(.//strong, "Warlock")]
