如何解决y脚:添加一些数学条件
使用python 3.8和scrapy 1.6,我要检查产品的星号是否等于或大于3.5,然后检查其他条件(如果discount_percent等于或大于10%),然后刮擦该产品的某些元素。我想问题是,刮掉的star和discount_percent元素是非英文数字,并且包含“%”。因此,尽管我使用utf8,但是当我将代码行包装在float()和int()函数中时,却得到以下日志:
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,3,179784)}
2020-08-19 15:53:22 [scrapy.core.engine] INFO: Spider closed (finished)
这是我的蜘蛛代码:
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
}
如何解决此问题?感谢您的帮助!
谢谢!
编辑:我做了答案1所说的,这是日志:
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,Platform Windows-10-10.0.19041-SP0
2020-08-19 17:25:19 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'digikala','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.logstats.LogStats']
2020-08-19 17:25:19 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware','scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-08-19 17:25:19 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware','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': 'کتاب تختخوابت را مرتب کن اثر ژنرال ویلیام اچ. مک ریون','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",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/response_bytes': 97086,12,55,24,181444),'item_scraped_count': 2,'log_count/DEBUG': 7,'log_count/INFO': 10,'spider_exceptions/AttributeError': 1,762866)}
2020-08-19 17:25:24 [scrapy.core.engine] INFO: Spider closed (finished)
这些是我在代码中所做的更改:
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(',''))
解决方法
问题出在您使用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())
不过,对于discounted_price
和original_price
,您还必须这样做,请确保没有诸如%
或货币符号之类的非数字字符。
这是因为您不能在使用非数字字符(例如int()
)的字符串上使用int("20%")
一种快速的解决方案是删除这些字符。对于discounted_percent
:
discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('٪',''))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。