Skip to main content
 首页 » 编程设计

python之Scrapy Xpath 输出为空

2025年04月02日19artech

我想在此网站上提取数据:http://www.pokepedia.fr/Pikachu 我正在学习 python 以及如何使用 Scrapy,我的问题是:为什么我无法使用 Xpath 检索数据?

当我在浏览器中测试 xpath 时,我的 Xpath 看起来不错,它返回正确的值。 (谷歌浏览器)

import re 
from scrapy import Spider 
from scrapy.selector import Selector 
 
from stack.items import StackItem 
 
 
class StackSpider(Spider): 
name = "stack" 
allowed_domains = ["pokepedia.fr"] 
start_urls = [ 
    "http://www.pokepedia.fr/Pikachu", 
] 
 
def unicodize(seg): 
    if re.match(r'\\u[0-9a-f]{4}', seg): 
        return seg.decode('unicode-escape') 
 
    return seg.decode('utf-8') 
 
def parse(self, response): 
    pokemon = Selector(response).xpath('//*[@id="mw-content-text"]/table[2]') 
 
    for question in pokemon: 
        item = StackItem() 
        item['title'] = question.xpath( 
            '//*[@id="mw-content-text"]/table[2]/tbody/tr[1]/th[2]/text()').extract()[0] 
        yield item 

我想在页面中提取宠物小 Sprite 的名称但是当我使用时:

scrapy crawl stack -o items.json -t json 

我的 Json 输出:

[ 

在我的控制台我有这个错误:

IndexError : list index out of range 

我遵循了这个教程:https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/

请您参考如下方法:

试试这个

question.xpath( '//*[@id="mw-content-text"]/table[2]/tr[1]/th[2]/text()').extract()[0] 

浏览器添加了 tbody 标签。它们不在原始 HTML 中,这就是 scrapy 返回空文件的原因。

PS:你可能要考虑使用

scrapy shell URL 

然后使用

response.xpath('...YOUR SELECTOR..') 

用于调试和测试。