首页 > 解决方案 > 无法使用 xml.etree.ElementTree 解析 html

问题描述

我正在尝试解析 google.com 的 xml,但是我收到了“格式不正确”的错误。为什么是这样?谢谢

➜  testing cat code.py
from urllib.request import urlopen; from xml.etree.ElementTree import fromstring
fromstring(urlopen('https://www.google.com').read().replace(b'<!doctype html>',b'<!DOCTYPE html>'))
➜  testing python3 code.py
Traceback (most recent call last):
  File "code.py", line 2, in <module>
    fromstring(urlopen('https://www.google.com').read().replace(b'<!doctype html>',b'<!DOCTYPE html>'))
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py", line 1315, in XML
    parser.feed(text)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 1826
➜  testing

标签: python-3.xxmlurllib

解决方案


您可能会收到错误消息,因为您尝试使用 XML 解析器解析 HTML;它行不通。尝试使用带有 HTML 解析器的库。另外,我建议改为获取带有请求的页面。所以一起:

import requests
import lxml.html as lh

req = requests.get('https://www.google.com')
lh.fromstring(req.text)

它应该可以工作。


推荐阅读