ValueError: Unicode strings with encoding declaration are not supported.

在寫爬蟲爬取網頁時遇到題目中的問題,完整錯誤如下:

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 supportedPlease use bytes input or XML fragments without declaration。

分析錯誤原因:

對於有encoding聲明的Unicode strings不支持。

解決辦法:

如報錯信息中所說,兩種方法:

  1. 如果是讀取的本地xml文件,需要將文件中的encoding declaration刪除。
  2. 如果是讀取網頁的,不能修改時,就將其轉換爲bytes類型。

修改後的代碼如下:

def getXpath(req, xpath):
    sourcehtml = etree.HTML(req.text.encode('utf-8'))
    print(sourcehtml)
    nodes = sourcehtml.xpath(xpath)
    return nodes

可以在網頁分析頁面看到encoding是什麼編碼,然後使用encode將其轉換爲bytes。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章