0

Using python 3.8 and scrapy 1.6, I want to check if a product's star is equal or more than 3.5 then check another condition (if the discount_percent is equal or more than 10%) then scrape some elements of that product. The problem is, I guess, scraped star and discount_percent elements are non-English numbers and contain "%". Thus, although I used utf8, when I wrap the code line in float() and int() functions I get this log:

2020-08-19 15:53:02 [scrapy.utils.log] INFO: Scrapy 1.6.0 started (bot: digikala)
2020-08-19 15:53:02 [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-08-19 15:53:02 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'digikala', 'FEED_FORMAT': 'csv', 'FEED_URI': 'dataset3.csv', 'NEWSPIDER_MODULE': 'digikala.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['digikala.spiders']}
2020-08-19 15:53:02 [scrapy.extensions.telnet] INFO: Telnet Password: 44549f4d62369441
2020-08-19 15:53:02 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats']
2020-08-19 15:53:03 [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']
2020-08-19 15:53:03 [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-08-19 15:53:03 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-08-19 15:53:03 [scrapy.core.engine] INFO: Spider opened
2020-08-19 15:53:03 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-08-19 15:53:03 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-08-19 15:53:09 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.digikala.com/robots.txt> (failed 1 times): 500 Internal Server Error
2020-08-19 15:53:10 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.digikala.com/robots.txt> (failed 2 times): 500 Internal Server Error
2020-08-19 15:53:11 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying <GET https://www.digikala.com/robots.txt> (failed 3 times): 500 Internal Server Error
2020-08-19 15:53:11 [scrapy.core.engine] DEBUG: Crawled (500) <GET https://www.digikala.com/robots.txt> (referer: None)
2020-08-19 15:53:21 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=incredible_offer&promotion_types[1]=promotion&pageno=1&last_filter=promotion_types&last_value=incredible_offer&sortby=4> (referer: None)
2020-08-19 15:53:21 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=incredible_offer&promotion_types[1]=promotion&pageno=1&last_filter=promotion_types&last_value=incredible_offer&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(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get())
ValueError: invalid literal for int() with base 10: '\n                                    ٪۲۹\n                                         '
2020-08-19 15:53:22 [scrapy.core.engine] INFO: Closing spider (finished)
2020-08-19 15:53:22 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1144,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 4,
 'downloader/response_bytes': 97181,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/500': 3,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 8, 19, 11, 23, 22, 803),
 'log_count/DEBUG': 5,
 'log_count/ERROR': 1,
 'log_count/INFO': 9,
 'response_received_count': 2,
 'retry/count': 2,
 'retry/max_reached': 1,
 'retry/reason_count/500 Internal Server Error': 2,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/500': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'spider_exceptions/ValueError': 1,
 'start_time': datetime.datetime(2020, 8, 19, 11, 23, 3, 179784)}
2020-08-19 15:53:22 [scrapy.core.engine] INFO: Spider closed (finished)

Here is my spider code:

    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(product.xpath(".//div[@class='c-product-box__engagement-rating']/text()").get())
            discounted_percent= int(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get())
            discounted_price= int(product.xpath(".//div[@class='c-price__value-wrapper']/text()").get())
            original_price= int(product.xpath(".//div[@class='c-price__value c-price__value--plp']/del/text()").get())
            url= response.urljoin(product.xpath(".//a[@class='js-product-url']/@href").get())
            if star>=3.5 and discounted_percent>=10:
                yield{
                    'title':title,
                    'star':star,
                    'discounted_percent':discounted_percent,
                    'discounted_price':discounted_price,
                    'original_price':original_price,
                    'url':url
                }

       

How can I fix the problem? I appreciate any help!

Thank you!!

EDIT: I did what is said in answer 1 and this is the log:

2020-08-19 17:25:19 [scrapy.utils.log] INFO: Scrapy 1.6.0 started (bot: digikala)
2020-08-19 17:25:19 [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-08-19 17:25:19 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'digikala', 'FEED_FORMAT': 'csv', 'FEED_URI': 'dataset3.csv', 'NEWSPIDER_MODULE': 'digikala.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['digikala.spiders']}
2020-08-19 17:25:19 [scrapy.extensions.telnet] INFO: Telnet Password: 75997283714aed4c
2020-08-19 17:25:19 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats']
2020-08-19 17:25:19 [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']
2020-08-19 17:25:19 [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-08-19 17:25:19 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-08-19 17:25:19 [scrapy.core.engine] INFO: Spider opened
2020-08-19 17:25:19 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-08-19 17:25:19 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-08-19 17:25:21 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.digikala.com/robots.txt> (failed 1 times): 500 Internal Server Error
2020-08-19 17:25:22 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.digikala.com/robots.txt> (failed 2 times): 500 Internal Server Error
2020-08-19 17:25:22 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying <GET https://www.digikala.com/robots.txt> (failed 3 times): 500 Internal Server Error
2020-08-19 17:25:22 [scrapy.core.engine] DEBUG: Crawled (500) <GET https://www.digikala.com/robots.txt> (referer: None)
2020-08-19 17:25:23 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=incredible_offer&promotion_types[1]=promotion&pageno=1&last_filter=promotion_types&last_value=incredible_offer&sortby=4> (referer: None)
2020-08-19 17:25:24 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=incredible_offer&promotion_types[1]=promotion&pageno=1&last_filter=promotion_types&last_value=incredible_offer&sortby=4>
{'title': 'کتاب خودت را به فنا نده اثر گری جان بیشاپ', 'star': 4.4, 'discounted_percent': 29, 'discounted_price': 12700, 'original_price': 18000, 'url': 'https://www.digikala.com/product/dkp-1050124/کتاب-خودت-را-به-فنا-نده-اثر-گری-جان-بیشاپ'}
2020-08-19 17:25:24 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=incredible_offer&promotion_types[1]=promotion&pageno=1&last_filter=promotion_types&last_value=incredible_offer&sortby=4>
{'title': 'کتاب تختخوابت را مرتب کن اثر ژنرال ویلیام اچ. مک ریون', 'star': 4.4, 'discounted_percent': 10, 'discounted_price': 13450, 'original_price': 15000, 'url': 'https://www.digikala.com/product/dkp-392946/کتاب-تختخوابت-را-مرتب-کن-اثر-ژنرال-ویلیام-اچ-مک-ریون'}
2020-08-19 17:25:24 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.digikala.com/search/category-book/?type[0]=4844&promotion_types[0]=incredible_offer&promotion_types[1]=promotion&pageno=1&last_filter=promotion_types&last_value=incredible_offer&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-08-19 17:25:24 [scrapy.core.engine] INFO: Closing spider (finished)
2020-08-19 17:25:24 [scrapy.extensions.feedexport] INFO: Stored csv feed (2 items) in: dataset3.csv
2020-08-19 17:25:24 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1144,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 4,
 'downloader/response_bytes': 97086,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/500': 3,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 8, 19, 12, 55, 24, 181444),
 'item_scraped_count': 2,
 'log_count/DEBUG': 7,
 'log_count/ERROR': 1,
 'log_count/INFO': 10,
 'response_received_count': 2,
 'retry/count': 2,
 'retry/max_reached': 1,
 'retry/reason_count/500 Internal Server Error': 2,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/500': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'spider_exceptions/AttributeError': 1,
 'start_time': datetime.datetime(2020, 8, 19, 12, 55, 19, 762866)}
2020-08-19 17:25:24 [scrapy.core.engine] INFO: Spider closed (finished)

These are the changes I made in the codes:

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(',', ''))
shima masaeli
  • 71
  • 1
  • 11

1 Answers1

0

The problem comes from the lines below that you are using int():

discounted_percent= int(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get())
discounted_price= int(product.xpath(".//div[@class='c-price__value-wrapper']/text()").get())
original_price= int(product.xpath(".//div[@class='c-price__value c-price__value--plp']/del/text()").get())
           

However you would also have to do this for discounted_price and original_price, making sure there are no non numerical characters such as % or currency symbols.

This is because you can't use int() on a string that uses non numerical characters such as int("20%")

A quick solution would be to remove these characters. In the case of discounted_percent:

discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('٪', ''))
Ryan
  • 2,167
  • 2
  • 28
  • 33
  • Thank you @Ryan, I edited the codes above. The prices had commas in between, so I changed their codes too. But it scraped only two products although there are more to be scraped. Is my condition wrong or should I do sth else? – shima masaeli Aug 19 '20 at 13:05
  • Is it possible that I got banned or sth like that? – shima masaeli Aug 19 '20 at 13:52
  • It ma be possible, take a look at this: https://docs.scrapy.org/en/latest/topics/practices.html#bans – Ryan Aug 19 '20 at 15:35