爬虫报出File “/home/xxx/testdemo/testdemo/xxx/lxxx.py”, line 40, in parse_page
modelt = info.split(r"路由器型号:")[-1]
TypeError: a bytes-like object is required, not ‘str’
2020-02-18 17:15:39 [scrapy.core.scraper] ERROR: Spider error processing <GET http://www.b-link.net.cn/download-detail.php?DId=75> (referer: http://xxxx/download.php?CateId=11&page=3)
bytes类型为python3新增的字节串类型,此时报出需要字节串而不是字符串,使用encode()函数将str类型转换为字节串类型,而decode()可将字节串转换为字符串。此时改为
modelt = info.encode().split(r"路由器型号:")[-1],由于上句语句已将info声明定义为bytes类型,又报出AttributeError: ‘bytes’ object has no attribute ‘encode’,此时又将上述语句改为modelt = info.decode().split(r"路由器型号:")[-1]后恢复正常。
其实上述方式绕远路了,python3已将字节串类型和字符串类型整合到str中可以将上述直接应用str函数对结果再做split即可,不需先encode再decode。
其中深层缘由也不甚清楚,这里只是分享实践试出来的一种方法