Reputation:
I am trying get the countries and national_debt from the website https://worldpopulationreview.com/country-rankings/countries-by-national-debt This is the code that I tried:
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()
}
And below is the result.
(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)
I do not know how to fix it. For example, I can get the title by the code In [3]: response.xpath("//h1/text()").get() Out[3]: 'Debt to GDP Ratio by Country 2022'
but with In [6]: response.xpath("//table/tbody/tr") Out[6]: [] I get nothing. Thx for helping.
Upvotes: 0
Views: 135
Reputation: 10460
First, your start-url
is wrong: Scrapy redirects it to a page where the table you're looking for is constructed dynamically. The information is loaded initially within page, however it remains trapped in script[@id="__NEXT_DATA__"]
, as Javascript cannot execute. You need to extract that script content as json, and then dissect it to get the info you need. See below an example:
class WorldpopSpider(scrapy.Spider):
name = 'worldpop'
allowed_domains = ['worldpopulationreview.com']
start_urls = ['https://worldpopulationreview.com/country-rankings/countries-by-national-debt']
def parse(self, response):
items = WorldpopdebtItem()
script_w_data = response.xpath('//script[@id="__NEXT_DATA__"]/text()').extract()[0]
data = json.loads(script_w_data)['props']['pageProps']['data']['customData']
for x in data:
yield x
Scrapy documentation can be found here: https://docs.scrapy.org/en/latest/
Upvotes: 2