You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy爬取国家债务数据无输出问题求助

问题:Scrapy爬取国家国债数据无输出,tbody XPath返回空列表

尝试爬取https://worldpopulationreview.com/country-rankings/countries-by-national-debt的国家名称与国债数据,编写Scrapy代码运行后无数据输出。能通过response.xpath("//h1/text()")获取页面标题,但response.xpath("//table/tbody/tr")返回空列表,求修复方案。


使用的代码

import scrapy


class GdpDebtSpider(scrapy.Spider):
    name = 'gdp_debt'
    allowed_domains = ['worldpopulationreview.com']
    start_urls = ['http://worldpopulationreview.com/countries/countries-by-national-debt/']

    def parse(self, response):
        rows = response.xpath("//table/tbody/tr")
        for row in rows:
            yield {
                'country_name': row.xpath(".//td[1]/a/text()").get(),
                'gdp_debt': row.xpath(".//td[2]/text()").get()
            }

运行日志

(virtual_workspace) C:\Users\Administrator\projects\national_debt>scrapy crawl gdp_debt   
2022-10-03 17:47:09 [scrapy.utils.log] INFO: Scrapy 2.6.2 started (bot: national_debt)
2022-10-03 17:47:09 [scrapy.utils.log] INFO: Versions: lxml 4.9.1.0, libxml2 2.9.14, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.2.0, Python 3.9.12 (main, Apr  4 2022, 05:22:27) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 1.1.1q  5 Jul 2022), cryptography 37.0.4, Platform Windows-10-10.0.19044-SP0
2022-10-03 17:47:09 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'national_debt',
 'NEWSPIDER_MODULE': 'national_debt.spiders',
 'ROBOTSTXT_OBEY': True,
 'SPIDER_MODULES': ['national_debt.spiders']}
2022-10-03 17:47:09 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2022-10-03 17:47:09 [scrapy.extensions.telnet] INFO: Telnet Password: e515af5c3d7daa7c
2022-10-03 17:47:09 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2022-10-03 17:47:10 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2022-10-03 17:47:10 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2022-10-03 17:47:10 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2022-10-03 17:47:10 [scrapy.core.engine] INFO: Spider opened
2022-10-03 17:47:10 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2022-10-03 17:47:10 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6024
2022-10-03 17:47:11 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://worldpopulationreview.com/robots.txt> (referer: None)
2022-10-03 17:47:11 [protego] DEBUG: Rule at line 1 without any user agent to enforce it on.
2022-10-03 17:47:11 [protego] DEBUG: Rule at line 2 without any user agent to enforce it on.
2022-10-03 17:47:11 [protego] DEBUG: Rule at line 4 without any user agent to enforce it on.
2022-10-03 17:47:11 [protego] DEBUG: Rule at line 7 without any user agent to enforce it on.
2022-10-03 17:47:11 [protego] DEBUG: Rule at line 10 without any user agent to enforce it on.
2022-10-03 17:47:11 [protego] DEBUG: Rule at line 12 without any user agent to enforce it on.
2022-10-03 17:47:11 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (308) to <GET https://worldpopulationreview.com/countries/countries-by-national-debt> from <GET https://worldpopulationreview.com/countries/countries-by-national-debt/>
2022-10-03 17:47:11 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (308) to <GET https://worldpopulationreview.com/country-rankings/countries-by-national-debt> from <GET https://worldpopulationreview.com/countries/countries-by-national-debt>
2022-10-03 17:47:11 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://worldpopulationreview.com/country-rankings/countries-by-national-debt> (referer: None)
2022-10-03 17:47:11 [scrapy.core.engine] INFO: Closing spider (finished)
2022-10-03 17:47:11 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1042,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 4,
 'downloader/response_bytes': 22963,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/308': 2,
 'downloader/response_status_count/404': 1,
 'elapsed_time_seconds': 0.52596,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2022, 10, 3, 10, 47, 11, 343361),
 'httpcompression/response_bytes': 78944,
 'httpcompression/response_count': 2,
 'log_count/DEBUG': 11,
 'log_count/INFO': 10,
 'response_received_count': 2,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/404': 1,
 'scheduler/dequeued': 3,
 'scheduler/dequeued/memory': 3,
 'scheduler/enqueued': 3,
 'scheduler/enqueued/memory': 3,
 'start_time': datetime.datetime(2022, 10, 3, 10, 47, 10, 817401)}
2022-10-03 17:47:11 [scrapy.core.engine] INFO: Spider closed (finished)

修复方案

核心原因

页面表格数据是JavaScript动态加载的,Scrapy默认下载的初始HTML中没有tbody内的行数据;另外浏览器会自动补全<tbody>标签,但实际返回的HTML里可能直接是<table>下嵌套<tr>,没有<tbody>。

方法1:直接爬取API接口(推荐)

通过浏览器开发者工具的Network面板可发现,页面数据来自一个JSON接口,直接请求接口更高效:

import scrapy
import json

class GdpDebtSpider(scrapy.Spider):
    name = 'gdp_debt'
    allowed_domains = ['worldpopulationreview.com']
    start_urls = ['https://worldpopulationreview.com/static/stats/rankings/countries-by-national-debt.json']

    def parse(self, response):
        data = json.loads(response.text)
        for item in data:
            yield {
                'country_name': item.get('country'),
                'gdp_debt': item.get('debt')
            }

方法2:用Scrapy+Selenium渲染JavaScript

如果必须模拟浏览器加载页面,可使用Selenium配合Scrapy:

  1. 安装依赖:pip install selenium,并下载对应浏览器的驱动(如ChromeDriver)
  2. 修改代码:
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from scrapy.http import HtmlResponse

class GdpDebtSpider(scrapy.Spider):
    name = 'gdp_debt'
    allowed_domains = ['worldpopulationreview.com']
    start_urls = ['https://worldpopulationreview.com/country-rankings/countries-by-national-debt']

    def __init__(self):
        chrome_options = Options()
        chrome_options.add_argument("--headless")  # 无头模式
        self.driver = webdriver.Chrome(options=chrome_options)

    def parse(self, response):
        self.driver.get(response.url)
        # 生成渲染后的HTML响应
        rendered_response = HtmlResponse(
            url=self.driver.current_url,
            body=self.driver.page_source,
            encoding='utf-8',
            request=response.request
        )
        # 直接定位table下的tr,跳过表头行
        rows = rendered_response.xpath("//table/tr")
        for row in rows[1:]:
            yield {
                'country_name': row.xpath(".//td[1]/a/text()").get(),
                'gdp_debt': row.xpath(".//td[2]/text()").get()
            }
        self.driver.quit()

额外提示

  • 检查初始HTML结构:执行scrapy shell https://worldpopulationreview.com/country-rankings/countries-by-national-debt进入交互模式,用view(response)打开页面查看实际返回的HTML,确认标签结构。
  • 关闭ROBOTSTXT_OBEY:日志显示robots.txt返回404,可在settings.py中设置ROBOTSTXT_OBEY = False避免不必要的请求。

内容的提问来源于stack exchange,提问作者user16786446

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:20:19