------------------3.10----------------------
關於爬取時,網頁編碼不是utf-8,而導致 lxml 輸出中文時亂碼的解決辦法
用requests.get拿到response,response.content是bytes的內容,所以可以直接傳給 lxml, body = etree.HTML(response.content)就不會有亂碼了
而response.text是返回unicode編碼的內容,需要進行編碼(encode),所以就是 body = etree.HTML(response.text.encode(response.encoding))
其實在python3中只要理解 str 和 bytes 的關系就夠了。
有一篇文章講得很好:http://www.ituring.com.cn/article/1116
ps:其實python3已經比python2少了很多很多編碼轉換的問題了。。。
在爬取某個網站時,直接用lxml.etree對response.content進行分析拿到的數據,與保存到本地后再分析拿到數據不一致
1 url = 'http://op.hanhande.com/mh/' 2 HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:51.0) Gecko/20100101 Firefox/51.0 '} 3 4 #直接分析 5 response = requests.get(url, headers=HEADERS) 6 body = etree.HTML(response.content) 7 us = body.xpath('//div[@class="mh_list_li"]/ul/li/a/@href') 8 ts = body.xpath('//div[@class="mh_list_li"]/ul/li/a/text()') 9 print(len(us), len(ts)) 10 #保存后分析 11 with codecs.open('body.html', 'w', encoding = response.encoding) as f: 12 f.write(response.content.decode(response.encoding)) 13 with codecs.open('body.html', 'r') as f: 14 body = f.read() 15 body = etree.HTML(body) 16 us = body.xpath('//div[@class="mh_list_li"]/ul/li/a/@href') 17 ts = body.xpath('//div[@class="mh_list_li"]/ul/li/a/text()') 18 print(len(us), len(ts))
運行結果為:
14 14
582 582
猜測可能是編碼的問題,但是不知道如何確定。
------------------3.08----------------------
文件非法命名的問題
在windows下如 ?\ * | “ < > : /;都是非法字符,不允許在文件名中出現,按正常來講,一旦出現這種情況,應該會有異常拋出,但是在使用pycharm的時候,這個異常並沒有被發現,而直接在cmd下運行python就會有異常拋出。
解決方法:
就是在創建文件時,對文件名進行判斷,如果有非法字符就替換調,如:str.replace('?', '')
請求超時的問題
1 try: 2 response = await self.session.get( 3 url, allow_redirects = False, headers=HEADERS 4 ) 5 break 6 except aiohttp.ClientError as client_error: 7 exception = client_error
這是500lines 里 crawl 的連接部分的一小段代碼,這個異常捕捉的確是可以捕捉到所有的連接異常,但是在實際運行中,超時異常並沒有被捕捉到,不知道是否因為是windows的鍋,但是后來再加上 except asyncio.TimeoutError 就可以捕捉到超時異常了。
ps:其實在看了源碼之后,aiohttp.TimeoutError也是繼承了 asyncio.TimeoutError的,那為什么aiohttp的就不能被捕捉到呢,待解決。