在寫爬蟲爬取網頁時遇到題目中的問題,完整錯誤如下:
def getXpath(req, xpath): sourcehtml = etree.HTML(req.text) print(sourcehtml) nodes = sourcehtml.xpath(xpath) return nodes
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration。
分析錯誤原因:
對於有encoding聲明的Unicode strings不支持。
解決辦法:
如報錯信息中所說,兩種方法:
- 如果是讀取的本地xml文件,需要將文件中的encoding declaration刪除。
- 如果是讀取網頁的,不能修改時,就將其轉換爲bytes類型。
修改後的代碼如下:
def getXpath(req, xpath): sourcehtml = etree.HTML(req.text.encode('utf-8')) print(sourcehtml) nodes = sourcehtml.xpath(xpath) return nodes
可以在網頁分析頁面看到encoding是什麼編碼,然後使用encode將其轉換爲bytes。