python lxml解析中文的問題
問題描述
使用lxml來抓取中文字符,抓到的結果很蛋疼,不知道怎么處理...
comUrl='http://m.51job.com/search/codetail.php?coid=4108723'res=requests.get(comUrl)html=etree.HTML(res.text)p=html.xpath('//aside')[1].xpath('./p') #結果為[<Element p at 0x7bf01c8>, <Element p at 0x78f4408>, <Element p at 0x69db388>]p[0].xpath('./span/text()') #這個是想要抓取的字符
結果抓到的是這樣的 [u’xe6x80xa7xe8xb4xa8’]unicode但是內容是str的編碼,請問怎么把這個東西轉成中文?正常應該是’xe6x80xa7xe8xb4xa8’或者u’u6027u8d28’
問題解答
回答1:’’.join(map(lambda x:chr(x), map(lambda x:ord(x), u’xe6x80xa7xe8xb4xa8’))).decode(’utf-8’)回答2:
出現這種情況,一般是requests猜錯了網頁的編碼了因此指定requests的編碼就可以了.res.encoding =’utf-8’
In [33]: comUrl='http://m.51job.com/search/codetail.php?coid=4108723' ...: res=requests.get(comUrl) ...: res.encoding =’utf-8’ ...: html=etree.HTML(res.text) ...: p=html.xpath('//aside')[1].xpath('./p') #結果為[<Element p at 0x7b ...: f01c8>, <Element p at 0x78f4408>, <Element p at 0x69db388>] ...: p[0].xpath('./span/text()') #這個是想要抓取的字符 ...: Out[33]: [u’u6027u8d28’]In [34]: print _[0]性質
相關文章:
1. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. html5 - 這個代碼顯示功能如何實現?3. java - 關于File的問題?4. java - instance method中 static后的<K>是什么意思?5. node.js - 終端 遠程連接服務器,終端關閉后,服務器無法運行6. 錯誤:java.lang.NoSuchMethodError:org.objectweb.asm.ClassWriter。<init>(I)V7. python3.x - python連oanda的模擬交易api獲取json問題第五問8. javascript - QWebEngineView 如何爬 angular 的動態數據?9. docker - 如何修改運行中容器的配置10. docker-machine添加一個已有的docker主機問題
