使用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'\xe6\x80\xa7\xe8\xb4\xa8']
unicode但是內容是str的編碼,請問怎麼把這個東西轉成中文?
正常應該是'\xe6\x80\xa7\xe8\xb4\xa8'或u'\u6027\u8d28'
滿天的星座2017-05-18 10:46:31
出現這種情況,一般是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'\u6027\u8d28']
In [34]: print _[0]
性质