lxml_解析錯誤ValueError


一:lxml解析錯誤

  • 1.報錯信息如下:
html=etree.HTML(xml)  --報錯的代碼行

ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
  • 錯誤原因:
使用request.get請求響應的數據使用的是
r.text   返回的是str(unicode)
#響應內容的前幾行如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">


  • 原因分析:
本來是html數據的,但是被設置成了xml的,還設置了'UTF-8'編碼
  • 解決方案
requests.get請求響應,返回content bytes類型
#這個位置可能會有問題(去掉了decode())
return response.content


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM