AttributeError:'NoneType'对象没有属性'strip'-Scrapy不会爬网所有元素

如何解决AttributeError:'NoneType'对象没有属性'strip'-Scrapy不会爬网所有元素

我的蜘蛛不会爬行所有元素。

如我现在所见,错误之一是属性错误,我不知道如何解决。这是一个非英语的网站,我希望将其数字转换为没有“%”和“,”的英语数字。当我询问时,建议我使用strip()和replace()。但是现在,问题出在AttributeError:'NoneType'对象没有属性'strip'

这是我得到的日志:

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': 'کتاب اثر مرکب اثر دارن هاردی نشر نسل نواندیش','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': 'کتاب مادر کافی اثر جی. ا. فرست','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': 'کتاب چهار میثاق اثر دون میگوئل روئیز','discounted_price': 15300,'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_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': 'کتاب قانون توانگری اثر کاترین پاندر انتشارات آلوس','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': 'کتاب برتری خفیف اثر جف اولسون','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,939691)}
2020-09-01 16:23:54 [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(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
                }

        

还有另一篇类似主题的文章,但我不知道该怎么办。可以帮我解决这个问题吗?

我还有另一个问题。上面的日志是什么意思?

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)

如果有帮助,我在settings.py中更改了ROBOTSTXT_OBEY = False

我还应该怎么做才能消除此错误?是因为URL的长度吗?还是什么?

谢谢

解决方法

 discounted_percent = int(str(product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get().strip()).replace('٪',''))
AttributeError: 'NoneType' object has no attribute 'strip'

这是告诉您discounted_percent中存储的内容是NoneType,换句话说,其值为None。由于None不是字符串,因此没有strip()方法。因此它会引发一个AttributeError

这将返回None,对于至少一种产品,其他产品似乎还不错:

product.xpath(".//div[@class='c-price__discount-oval']/span/text()").get()

您可能需要在调用.strip()之前检查它是否返回了一个值,或者甚至更好的方法是在其他地方进行所有此处理。

关于其他问题:

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)

这不是问题,这只是一条调试消息,告诉您蜘蛛抓取了提到的页面。如果您不想看到调试消息,可以在LOG_LEVEL='INFO'

中设置settings.py

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-