'AttributeError: 'NoneType' object has no attribute 'strip' - Scrapy doesn't crawl all the elements
My spider doesn't crawl all the elements.
As I can see now, one of the errors is an attribute error which I don't know how to fix it. This is a non-English website that I want its numbers to be turned as English ones without "%" and ",". When I asked, I was recommended to use strip() and replace(). But now, the problem is AttributeError: 'NoneType' object has no attribute 'strip'
This was the log I got:
2020-09-01 16:23:53 [scrapy.utils.log] INFO: Scrapy 1.6.0 started (bot: digikala)
2020-09-01 16:23:53 [scrapy.utils.log] INFO: Versions: lxml 4.5.2.0, libxml2 2.9.10, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 20.3.0, Python 3.8.5 (default, Aug 5 2020, 09:44:06) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1g 21 Apr 2020), cryptography 2.9.2, Platform Windows-10-10.0.19041-SP0
2020-09-01 16:23:53 [scrapy.crawler] INFO: Overridden settings: {'AUTOTHROTTLE_MAX_DELAY': 120, 'AUTOTHROTTLE_START_DELAY': 60, 'BOT_NAME': 'digikala', 'FEED_FORMAT': 'xml', 'FEED_URI': '99-6-11-12.xml', 'NEWSPIDER_MODULE': 'digikala.spiders', 'SPIDER_MODULES': ['digikala.spiders']}
2020-09-01 16:23:53 [scrapy.extensions.telnet] INFO: Telnet Password: 87dd5cd5e47f9a7a
2020-09-01 16:23:53 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.feedexport.FeedExporter',
'scrapy.extensions.logstats.LogStats']
2020-09-01 16:23:53 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'digikala.middlewares.UserAgentRotatorMiddleware',
'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']
2020-09-01 16:23:53 [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']
2020-09-01 16:23:53 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-09-01 16:23:53 [scrapy.core.engine] INFO: Spider opened
2020-09-01 16:23:53 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-09-01 16:23:53 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-09-01 16:23:54 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4> (referer: None)
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب خودت را به فنا نده اثر گری جان بیشاپ', 'star': 4.4, 'discounted_percent': 28, 'discounted_price': 13000, 'original_price': 18000, 'discounted_amount': 5000, 'url': 'https://www.digikala.com/product/dkp-1050124/کتاب-خودت-را-به-فنا-نده-اثر-گری-جان-بیشاپ'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب شرمنده نباش دختر اثر ریچل هالیس نشر کتاب کوله پشتی', 'star': 4.6, 'discounted_percent': 15, 'discounted_price': 25500, 'original_price': 30000, 'discounted_amount': 4500, 'url': 'https://www.digikala.com/product/dkp-1556940/کتاب-شرمنده-نباش-دختر-اثر-ریچل-هالیس-نشر-کتاب-کوله-پشتی'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب شفای زندگی اثر لوییز هی', 'star': 4.5, 'discounted_percent': 21, 'discounted_price': 50500, 'original_price': 64000, 'discounted_amount': 13500, 'url': 'https://www.digikala.com/product/dkp-137593/کتاب-شفای-زندگی-اثر-لوییز-هی'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب اثر مرکب اثر دارن هاردی نشر نسل نواندیش', 'star': 4.6, 'discounted_percent': 15, 'discounted_price': 32200, 'original_price': 37900, 'discounted_amount': 5700, 'url': 'https://www.digikala.com/product/dkp-1808376/کتاب-اثر-مرکب-اثر-دارن-هاردی-نشر-نسل-نواندیش'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب مادر کافی اثر جی. ا. فرست', 'star': 4.5, 'discounted_percent': 15, 'discounted_price': 49300, 'original_price': 58000, 'discounted_amount': 8700, 'url': 'https://www.digikala.com/product/dkp-38932/کتاب-مادر-کافی-اثر-جی-ا-فرست'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب چهار میثاق اثر دون میگوئل روئیز', 'star': 4.6, 'discounted_percent': 15, 'discounted_price': 15300, 'original_price': 18000, 'discounted_amount': 2700, 'url': 'https://www.digikala.com/product/dkp-37451/کتاب-چهار-میثاق-اثر-دون-میگوئل-روئیز'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب نمی گذارم کسی اعصابم را به هم بریزد اثر آلبرت الیس', 'star': 4.3, 'discounted_percent': 15, 'discounted_price': 39000, 'original_price': 45900, 'discounted_amount': 6900, 'url': 'https://www.digikala.com/product/dkp-38145/کتاب-نمی-گذارم-کسی-اعصابم-را-به-هم-بریزد-اثر-آلبرت-الیس'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب قانون توانگری اثر کاترین پاندر انتشارات آلوس', 'star': 4.5, 'discounted_percent': 68, 'discounted_price': 22100, 'original_price': 70000, 'discounted_amount': 47900, 'url': 'https://www.digikala.com/product/dkp-2359806/کتاب-قانون-توانگری-اثر-کاترین-پاندر-انتشارات-آلوس'}
2020-09-01 16:23:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
{'title': 'کتاب برتری خفیف اثر جف اولسون', 'star': 4.5, 'discounted_percent': 15, 'discounted_price': 38200, 'original_price': 45000, 'discounted_amount': 6800, 'url': 'https://www.digikala.com/product/dkp-141776/کتاب-برتری-خفیف-اثر-جف-اولسون'}
2020-09-01 16:23:54 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4> (referer: None)
Traceback (most recent call last):
File "C:\Users\shima\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback
yield next(it)
File "C:\Users\shima\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output
for x in result:
File "C:\Users\shima\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in <genexpr>
return (_set_referer(r) for r in result or ())
File "C:\Users\shima\anaconda3\envs\virtual_workspace\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr>
return (r for r in result or () if _filter(r))
File "C:\Users\shima\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\shima\projects\digikala\digikala\spiders\promotions.py", line 23, in parse
discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('٪', ''))
AttributeError: 'NoneType' object has no attribute 'strip'
2020-09-01 16:23:54 [scrapy.core.engine] INFO: Closing spider (finished)
2020-09-01 16:23:54 [scrapy.extensions.feedexport] INFO: Stored xml feed (9 items) in: 99-6-11-12.xml
2020-09-01 16:23:54 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 390,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 81890,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2020, 9, 1, 11, 53, 54, 883694),
'item_scraped_count': 9,
'log_count/DEBUG': 10,
'log_count/ERROR': 1,
'log_count/INFO': 10,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'spider_exceptions/AttributeError': 1,
'start_time': datetime.datetime(2020, 9, 1, 11, 53, 53, 939691)}
2020-09-01 16:23:54 [scrapy.core.engine] INFO: Spider closed (finished)
This is my spider:
def parse(self, response):
for product in response.xpath("//ul[@class='c-listing__items']/li"):
title= product.xpath(".//a[@class='js-product-url']/text()").get()
star= float(str(product.xpath(".//div[@class='c-product-box__engagement-rating']/text()").get()))
discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('٪', ''))
discounted_price= int(str(product.xpath(".//div[@class='c-price__value-wrapper']/text()").get().strip()).replace(',', ''))
original_price= int(str(product.xpath(".//div[@class='c-price__value c-price__value--plp']/del/text()").get().strip()).replace(',', ''))
url= response.urljoin(product.xpath(".//a[@class='js-product-url']/@href").get())
discounted_amount= original_price-discounted_price
if star>=3.5 and (discounted_amount>=5000 or discounted_percent>=10):
yield{
'title':title,
'star':star,
'discounted_percent':discounted_percent,
'discounted_price':discounted_price,
'original_price':original_price,
'discounted_amount': discounted_amount,
'url':url
}
There is another post with a similar topic, but I couldn't understand what to do. Can some help me out with this problem?
I have another problem. what does it mean in the above log?
2020-09-01 16:23:54 [scrapy.core.engine] DEBUG: Crawled (200) <GET
https://www.digikala.com/search/category-book/?type[0]=
4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
(referer: None)
I changed ROBOTSTXT_OBEY = False in settings.py if it helps
What else should I do to remove this error? Is it because of the length of the URL? or what?
Thank you
Solution 1:[1]
discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('?', ''))
AttributeError: 'NoneType' object has no attribute 'strip'
This is telling you that what is stored inside discounted_percent
is of NoneType, in other words it's value is None
. Since None
isn't a string, there is no strip()
method. Therefore it raises an AttributeError
This is returning None
, for at least ONE of the products, the others seems fine:
product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get()
You may need to check if it returned a value before calling .strip()
, or even better, do all this processing somewhere else.
About your other question:
2020-09-01 16:23:54 [scrapy.core.engine] DEBUG: Crawled (200) <GET
https://www.digikala.com/search/category-book/?type[0]=
4844&promotion_types[0]=promotion&pageno=1&last_filter=promotion_types&last_value=promotion&sortby=4>
(referer: None)
This isn't a problem, it's just a debug message telling you the spider crawled the page mentioned. If you don't want to see debug messages you can set LOG_LEVEL='INFO'
in your settings.py
Solution 2:[2]
.strip() method only works with strings, and some of your parsed elements are returning None values.
You could use a turnaround to solve this by assigning empty strings as default return value, like this:
.get(default='')
This will get you an empty string instead of a None object. See scrapy 'Selectors' documentation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | renatodvc |
Solution 2 | José Tomás Sierra |