I'm trying to code a spider that takes name, gdp and countries' birth and death values but I can't find where is the error or a solution for an error while processing the starting url, don't know if it's a problem with xpath or other thing, most of the threads that I found about talks about wrong indentation, but this is not my case.
Code:
import scrapy
import logging
class GdpsSpider(scrapy.Spider):
name = 'gdps'
allowed_domains = ['www.worldpopulationreview.com']
start_urls = ['https://worldpopulationreview.com/countries/countries-by-national-debt/']
def parse(self, response):
countries = response.xpath('//tr')
for country in countries:
name = country.xpath(".//td[1]/a/text()").get()
link = country.xpath(".//td[1]/a/@href").get()
gdp = country.xpath(".//td[2]/text()").get()
# yield{
# 'name': name,
# 'gdp': gdp,
# 'link': link
# }
yield response.follow(url=link, callback=self.parse_bd, meta={'name':name, 'gdp':gdp})
def parse_bd(self, response):
name = response.request.meta['name']
gdp = response.request.meta['gdp']
# rows = response.xpath('//*[@id="popClock"]/div/div[1]/div/div/table/tbody')
rows = response.xpath("(//table[@class='table table-striped'])[1]/tbody")
for row in rows:
births = row.xpath(".//tr[3]/td[@class='number']/text()").get()
deaths = row.xpath(".//tr[4]/td[@class='number']/text()").get()
yield{
'name': name,
'gdp': gdp,
'births': births,
'deaths': deaths
}
Error:
(virtual_workspace) C:\Users\Bugra\projects\gdp>scrapy crawl gdps
2022-04-12 21:43:57 [scrapy.utils.log] INFO: Scrapy 2.6.1 started (bot: gdp)
2022-04-12 21:43:57 [scrapy.utils.log] INFO: Versions: lxml 4.8.0.0, libxml2 2.9.10, 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.1n 15 Mar 2022), cryptography 36.0.2, Platform Windows-10-10.0.22000-SP0
2022-04-12 21:43:57 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'gdp',
'NEWSPIDER_MODULE': 'gdp.spiders',
'ROBOTSTXT_OBEY': True,
'SPIDER_MODULES': ['gdp.spiders']}
2022-04-12 21:43:57 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2022-04-12 21:43:57 [scrapy.extensions.telnet] INFO: Telnet Password: 10f8998db04ef71d
2022-04-12 21:43:57 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.logstats.LogStats']
2022-04-12 21:43:57 [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-04-12 21:43:57 [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-04-12 21:43:57 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2022-04-12 21:43:57 [scrapy.core.engine] INFO: Spider opened
2022-04-12 21:43:57 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2022-04-12 21:43:57 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2022-04-12 21:43:58 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (307) to <GET https://worldpopulationreview.com/robots.txt> from <GET https://www.worldpopulationreview.com/robots.txt>
2022-04-12 21:43:58 [py.warnings] WARNING: C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\core\engine.py:276: ScrapyDeprecationWarning: Passing a 'spider' argument to ExecutionEngine.download is deprecated
return self.download(result, spider) if isinstance(result, Request) else result
2022-04-12 21:43:58 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://worldpopulationreview.com/robots.txt> (referer: None)
2022-04-12 21:43:58 [protego] DEBUG: Rule at line 1 without any user agent to enforce it on.
2022-04-12 21:43:58 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (307) to <GET https://worldpopulationreview.com/countries/countries-by-national-debt/> from <GET https://www.worldpopulationreview.com/countries/countries-by-national-debt/>
2022-04-12 21:43:58 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://worldpopulationreview.com/robots.txt> (referer: None)
2022-04-12 21:43:58 [protego] DEBUG: Rule at line 1 without any user agent to enforce it on.
2022-04-12 21:43:58 [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-04-12 21:43:58 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://worldpopulationreview.com/countries/countries-by-national-debt> (referer: None)
2022-04-12 21:43:58 [scrapy.core.scraper] ERROR: Spider error processing <GET https://worldpopulationreview.com/countries/countries-by-national-debt> (referer: None)
Traceback (most recent call last):
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\utils\defer.py", line 132, in iter_errback
yield next(it)
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\utils\python.py", line 354, in __next__
return next(self.data)
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\utils\python.py", line 354, in __next__
return next(self.data)
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\core\spidermw.py", line 66, in _evaluate_iterable
for r in iterable:
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output
for x in result:
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\core\spidermw.py", line 66, in _evaluate_iterable
for r in iterable:
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 342, in <genexpr>
return (_set_referer(r) for r in result or ())
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\core\spidermw.py", line 66, in _evaluate_iterable
for r in iterable:
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 40, in <genexpr>
return (r for r in result or () if _filter(r))
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\core\spidermw.py", line 66, in _evaluate_iterable
for r in iterable:
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr>
return (r for r in result or () if _filter(r))
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\core\spidermw.py", line 66, in _evaluate_iterable
for r in iterable:
File "C:\Users\Bugra\projects\gdp\gdp\spiders\gdps.py", line 22, in parse
yield response.follow(url=link, callback=self.parse_bd, meta={'name':name, 'gdp':gdp})
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\http\response\text.py", line 158, in follow
return super().follow(
File "C:\Users\Bugra\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\http\response\__init__.py", line 163, in follow
raise ValueError("url can't be None")
ValueError: url can't be None
2022-04-12 21:43:58 [scrapy.core.engine] INFO: Closing spider (finished)
2022-04-12 21:43:58 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1522,
'downloader/request_count': 6,
'downloader/request_method_count/GET': 6,
'downloader/response_bytes': 17956,
'downloader/response_count': 6,
'downloader/response_status_count/200': 1,
'downloader/response_status_count/307': 2,
'downloader/response_status_count/308': 1,
'downloader/response_status_count/404': 2,
'elapsed_time_seconds': 1.021947,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2022, 4, 12, 18, 43, 58, 619959),
'httpcompression/response_bytes': 56201,
'httpcompression/response_count': 3,
'log_count/DEBUG': 9,
'log_count/ERROR': 1,
'log_count/INFO': 10,
'log_count/WARNING': 1,
'response_received_count': 3,
'robotstxt/request_count': 2,
'robotstxt/response_count': 2,
'robotstxt/response_status_count/404': 2,
'scheduler/dequeued': 3,
'scheduler/dequeued/memory': 3,
'scheduler/enqueued': 3,
'scheduler/enqueued/memory': 3,
'spider_exceptions/ValueError': 1,
'start_time': datetime.datetime(2022, 4, 12, 18, 43, 57, 598012)}
2022-04-12 21:43:58 [scrapy.core.engine] INFO: Spider closed (finished)
CodePudding user response:
I just figured it out. I changed my allowed domains
allowed_domains = ['www.worldpopulationreview.com']
to
allowed_domains = ['worldpopulationreview.com']
allowed domains only accepts domains not URL's.
CodePudding user response:
ValueError("url can't be None") beacuse of relative urls.So you have to make them absolute url as follows:
import scrapy
from scrapy.crawler import CrawlerProcess
import logging
class GdpsSpider(scrapy.Spider):
name = 'gdps'
allowed_domains=['worldpopulationreview.com']
start_urls = ['https://worldpopulationreview.com/countries/countries-by-national-debt']
def parse(self, response):
countries = response.xpath('//tr')
for country in countries:
name = country.xpath(".//td[1]/a/text()").get()
link = country.xpath(".//td[1]/a/@href").get()
abs_url='https://worldpopulationreview.com' str(link)
gdp = country.xpath(".//td[2]/text()").get()
yield{
'name': name,
'gdp': gdp,
'link': abs_url
}
if __name__ == "__main__":
process = CrawlerProcess({'USER_AGENT': 'Mozilla/5.0'})
process.crawl(GdpsSpider)
process.start()
Output:
{'name': 'Japan', 'gdp': '237.54%', 'link': 'https://worldpopulationreview.com/countries/japan-population'}
2022-04-13 02:15:17 [scrapy.core.scraper] DEBUG: Scraped from <200 https://worldpopulationreview.com/countries/countries-by-national-debt>
{'name': 'Venezuela', 'gdp': '214.45%', 'link': 'https://worldpopulationreview.com/countries/venezuela-population'}
2022-04-13 02:15:17 [scrapy.core.scraper] DEBUG: Scraped from <200 https://worldpopulationreview.com/countries/countries-by-national-debt>
{'name': 'Sudan', 'gdp': '177.87%', 'link': 'https://worldpopulationreview.com/countries/sudan-population'}
2022-04-13 02:15:17 [scrapy.core.scraper] DEBUG: Scraped from <200 https://worldpopulationreview.com/countries/countries-by-national-debt>
{'name': 'Greece', 'gdp': '174.15%', 'link': 'https://worldpopulationreview.com/countries/greece-population'}
2022-04-13 02:15:17 [scrapy.core.scraper] DEBUG: Scraped from <200 https://worldpopulationreview.com/countries/countries-by-national-debt>
{'name': 'Lebanon', 'gdp': '157.81%', 'link': 'https://worldpopulationreview.com/countries/lebanon-population'}