python-3.x - 无法使用 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
解决方案
您可能会收到错误消息,因为您尝试使用 XML 解析器解析 HTML;它行不通。尝试使用带有 HTML 解析器的库。另外,我建议改为获取带有请求的页面。所以一起:
import requests
import lxml.html as lh
req = requests.get('https://www.google.com')
lh.fromstring(req.text)
它应该可以工作。
推荐阅读
- c - C - 如何为结构内的链表分配内存
- java - Spring PetClinic 应用程序在 pom.xml 中显示错误
- ruby - 使用“attr_accessor”定义非标准访问器方法
- node.js - 未下载 Chromium 修订版。在 Electron 构建中的 Launcher.launch 运行“npm install”或“yarn install”
- android - 从上到下淡入/淡出视图,反之亦然,而无需使用 Scale 平移或缩小视图
- python - 放置一个额外的 minimum_cost_node = None 来做变量声明
- c++ - 按多个属性排序
- javascript - Promise.all Error: Uncaught (in promise) TypeError: #
不可迭代 - angular - 尝试在 Angular 中创建可重用表单组件时出错
- linux - curl命令有时没有响应输出,有时有?