python3_爬取bug集

目录

        • 程序bug集
          • 1、爬取内容显示乱码
          • 2、pymongo.errors.CursorNotFound:
          • 3、TypeError: can't pickle _thread.lock objects和EOFError: Ran out of input
          • 4、redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a byte, string or number first.
          • 5、json.dumps()中文未正确显示
          • 6、AttributeError: 'NoneType' object has no attribute 'decode'
          • 7、如果代理设置成功,最后显示的IP应该是代理的IP地址,但是最终还是我真实的IP地址,为什么?

程序bug集
  • 1、python爬取内容显示乱码
  • 2、pymongo.errors.CursorNotFound:cursor id 64638209105 not found
  • 3、TypeError: can’t pickle _thread.lock objects 和 EOFError: Ran out of input
  • 4、redis.exceptions.DataError: Invalid input of type: ‘dict’. Convert to a byte, string or number first.
  • 5、json.dumps()中文未正确显示
  • 6、AttributeError: ‘NoneType’ object has no attribute ‘decode’
  • 7、如果代理设置成功,最后显示的IP应该是代理的IP地址,但是最终还是我真实的IP地址,为什么?
1、爬取内容显示乱码
  • (1)原因:
1、原因:比如网页编码是gbk编码的,但是我们用了错误的方式比如utf-8解码,因而出现乱码
2、基础知识:
	(1)python3.6 默认编码为Unicode;正常的字符串就是Unicode
	(2)计算机中存储的信息都是二进制的
	(3)编码decode:真实字符→二进制
	(4)解码encode:二进制→真实字符
	(5)一般来说在Unicode2个字节的,在UTF8需要3个字节;但对于大多数语言来说,只需要1个字节就能编码,如果采用Unicode会极大浪费,于是出现了变长的编码格式UTF8
	(6)GB2312的出现,基本满足了汉字的计算机处理需要,但对于人名、古汉语等方面出现的罕用字,GB2312不能处理,这导致了后来GBK及GB18030汉字字符集的出现。	
3、各种编码方式:
	(1)ASCII :1字节8个bit位表示一个字符的编码格式,最多可以给256个字(包括字母、数字、标点符号、控制字符及其他符号)分配(或指定)数值。
	(2)ISO8859-11字节8个bit位表示一个字符的编码格式,仅支持英文字符、数字及常见的符号,3.6%的全球网站使用这个编码。
	(3)GB2312:2字节16个bit位表示一个字符的编码格式,基本满足了汉字的计算机处理需要
	(4)GBK:2字节16个bit位表示一个字符的编码格式,GBK即汉字内码扩展规范
	(5)Unicode :2字节16个bit位表示一个字符的编码格式,基本能把全球所有字符表示完,
	(6)UTF8:变长字节编码格式,英文1字节,汉字3字节,较复杂的更高字节编码,
4、实例:
s = "好" #默认Unicode编码
print(s.encode("gbk")) #Unicode转gbk
#输出2字节: b'\xba\xc3'
print(s.encode("utf-8")) #Unicode转utf-8
#输出3字节:b'\xe5\xa5\xbd'
print(s.encode("gb2312")) #Unicode转gb2312
#输出2字节:b'\xba\xc3'
print(s.encode("gb2312").decode("gb2312")) #Unicode解码为gb2312再编码为Unicode
print(s.encode("utf8").decode("utf8")) #Unicode解码为utf8再编码为Unicode
#输出:好
  • (2)解决方法
方法:
	查看网页是什么编码,并设置该编码格式,或者包含大于这个的编码,如gb2312编码的网页可以设置gbk的编码方式。
代码:
	solution1:response.encoding = response.apparent_encoding
	solution2 :response.encoding = 'utf-8'
		    	response.encoding = 'gbk'
2、pymongo.errors.CursorNotFound:
  • (1)原因:
1、原因:默认 mongo server维护连接的时间窗口是十分钟;默认单次从server获取数据是101条或者 大于1M小于16M的数据;所以默认情况下,如果10分钟内未能处理完数据,则抛出该异常。
  • (2)解决方法:
方法:
	no_cursor_timeout=True:设置连接永远不超时
	batch_size:估计每批次获取数据量的条数;让MongoDB客户端每次抓取的文档在10分钟内能用完
代码:
	import pymongo
	client = pymongo.MongoClient(host='localhost', port=27017)
    db = client.test
	collection = db.testtable
	cursor = collection.find(no_cursor_timeout=True, batch_size=5)
3、TypeError: can’t pickle _thread.lock objects和EOFError: Ran out of input
  • (1)原因:
1、进程池内部处理使用了pickle模块(用于python特有的类型和python的数据类型间进行转换)中的dump(obj, file, protocol=None,)方法对参数进行了封装处理.
2、在参数传递中如果自定义了数据库存储类mongo或者redis等数据库,会造成进程池内部处理封装过程无法对其进行处理. 
3、错误代码产生异常的实例1import multiprocessing
	import pymongo
	class Test:
	    def __init__(self, collection):
	        self.collection = collection
	    def savedata(self):
	        self.collection.insert_one({'key': 'value'})
	def main():
	    client = pymongo.MongoClient(host='localhost', port=27017)
	    db = client.test
	    collecttable = db.testtable
	    test = Test(collecttable)
	    p1 = multiprocessing.Process(target=test.savedata)
	    p1.start()
	    p1.join()
	    print('进程已结束')
	if __name__ == '__main__':
	    main()
4、错误代码产生异常的实例2import multiprocessing
	import pymongo
	class Test:
	    def __init__(self):
	        pass
	    def savedata(self, collecttable):
	        collecttable.insert_one({'key': 'value'})
	def main():
	    client = pymongo.MongoClient(host='localhost', port=27017)
	    db = client.test
	    collecttable = db.testtable
	    test = Test()
	    p1 = multiprocessing.Process(target=test.savedata, args=(collecttable,))
	    p1.start()
	    p1.join()
	    print('进程已结束')
	if __name__ == '__main__':
	    main()
  • (2)解决方法:
方法:
	在参数传递时,不能将数据库集合作为类的参数进行传递,只能在函数里面创建使用数据库
代码:
	import multiprocessing
	import pymongo
	class Test:
	    def __init__(self):
	        pass
	    def savedata(self):
	        client = pymongo.MongoClient(host='localhost', port=27017)
	        db = client.test
	        collecttable = db.testtable
	        collecttable.insert_one({'key': 'value'})
	def main():
	    test = Test()
	    p1 = multiprocessing.Process(target=test.savedata)
	    p1.start()
	    p1.join()
	    print('进程已结束')
	if __name__ == '__main__':
	    main()
4、redis.exceptions.DataError: Invalid input of type: ‘dict’. Convert to a byte, string or number first.
  • (1)原因:
1、redis存入数据类型错误,应该是字节或者是字符串或者是数字类型
2、错误实例:
	from redis import StrictRedis
	dict = {'key': 'value'}
	r = StrictRedis(host='localhost', port=6379)
	r.rpush('test', dict)
  • (2)解决方法:
方法:
	使用json模块,json.dumps(dict)可以将字典类型的转换为字符串
代码:
	import json
	from redis import StrictRedis
	dict = {'key': 'value'}
	r = StrictRedis(host='localhost', port=6379)
	data = json.dumps(dict)
	r.rpush('test', data)
	print(r.lpop('test'))
	#输出: b'{"key": "value"}'
5、json.dumps()中文未正确显示
  • (1)原因:
1、json.dumps序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False2、实例代码:
	import json
	dict = {'key': '测试'}
	print(json.dumps(dict))
	# 输出:{"key": "\u6d4b\u8bd5"}
  • (2)解决方法:
方法:
	json.dumps(dict,ensure_ascii = False)
代码:
	import json
	dict = {'key': '测试'}
	print(json.dumps(dict, ensure_ascii=False))
	#输出: {"key": "测试"}
6、AttributeError: ‘NoneType’ object has no attribute ‘decode’
  • (1)原因:
1、redis数据库为空,未取到数据,返回类型是NoneType类型
2、错误实例:
	from redis import StrictRedis
	r = StrictRedis(host='localhost', port=6379)
	print(r.lpop('test').decode('utf-8'))
  • (2)解决方法:
1、确保redis里面有数据,先存数据,再取数据
2、代码:
	import json
	from redis import StrictRedis
	r = StrictRedis(host='localhost', port=6379)
	dict = {'key': '测试'}
	data = json.dumps(dict, ensure_ascii=False)
	r.rpush('test', data)
	print(r.lpop('test').decode('utf-8')) #redis取出来的数据为字节类型,需要编码decode
	#输出:{"key": "测试"}
7、如果代理设置成功,最后显示的IP应该是代理的IP地址,但是最终还是我真实的IP地址,为什么?
  • 获取代理并检测有效性
  • (1)原因:
requests.get(url,headers=headers,proxies=proxies)
1、proxies在你访问http协议的网站时用http代理,访问https协议的网站用https的代理
2、所以你的proxy需要根据网站是http还是https的协议进行代理设置,这样才能生效
  • (2)解决方法:
1、方法:
	如果proxies ={'http': 'http://112.85.169.206:9999'},
	http的测试网站'http://icanhazip.com'
	如果proxies ={'https': 'https://112.85.129.89:9999'}
	https的测试网站https://www.baidu.com/
2、代码:
	proxies ={'http': 'http://112.85.169.206:9999'}
	r = requests.get('http://icanhazip.com', headers=headers, proxies=proxies, timeout=2)
	proxies ={'https': 'https://112.85.129.89:9999'}
	r = requests.get('https://www.baidu.com/', headers=headers, proxies=proxies, timeout=2)
···

你可能感兴趣的:(#,Bug)