碎片蜘蛛没有提取xpath d

2024-04-19 23:13:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手。我通常使用php来抓取数据。我想换成python。我从这里开始学习教程。

http://doc.scrapy.org/en/latest/intro/tutorial.html

我想从这个维基百科页面抓取国家和首都。 https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order

我的蜘蛛程序是:

import scrapy

class CountrySpider(scrapy.Spider):
    name = "countryCapitals"
    allowed_domains = ["wikipedia.org"]
    start_urls = [
                    "https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order"
                    ]

    def parse(self, response):
            for sel in response.xpath('//*[@id="mw-content-text"]/table[2]/tbody/tr'):
                    country = sel.xpath('//td[1]').extract()
                    capital = sel.xpath('td[2]/b/span.text()').extract()
                    print country , capital

它没有按预期打印任何数据。如有任何帮助,我们将不胜感激。


Tags: of数据inhttpsorgwikiwikipediaxpath
2条回答

似乎浏览器控制台中显示的HTML与原始源代码有些不同。例如,@furas指出,tdoby标记就是问题的一部分。但用于提取大写文本的xpath也不正确。在

我用下面的parse方法做了一个测试,效果很好,为了提取国家文本,我还更改了country xpath。在

def parse(self, response):
        for sel in response.xpath('//*[@id="mw-content-text"]/table[2]/tr'):
                country = sel.xpath('td[1]/a/text()').extract()
                capital = sel.xpath('td[2]//a/text()').extract()
                print country , capital

部分输出示例:

^{pr2}$

我测试了你的代码。我想问题出在你的xpath上。我假设您正在使用chrome功能来复制xpath。 我自己也不擅长xpath。我尝试使用.css()方法将值打印出来。我用过:

print response.css('div.mw-content-ltr > table').extract()

它工作得很好。把id放在表的第二行。我相信它应该能正常工作。在

相关问题 更多 >