无法使用 xml.etree.ElementTree 解析 html

Can't parse html using xml.etree.ElementTree

我正在尝试解析 google.com 的 xml,但是我收到 'not well-formed' 错误。为什么是这样?谢谢

➜  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

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

import requests
import lxml.html as lh

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

它应该可以工作。