python - xml.etree.ElementTree.ParseError : not well-formed (invalid token) due to "<" symbol in script

标签 python xml xml-parsing

我正在尝试解析网页以将其中的一些数据保存在 Excel 或 csv 文件中。

import urllib.request
import xml.etree.ElementTree as ET

url = "http://rusdrama.com/afisha"
response = urllib.request.urlopen(url)
content = response.read()
root = ET.fromstring(content)

使用 fromstring 方法 ElementTree 解析页面时出现以下错误:

Traceback (most recent call last):
  File "D:/PythonProjects/PythonMisc/theater_reader.py", line 7, in <module>
    root = ET.fromstring(content)
  File "D:\Python\Python35\lib\xml\etree\ElementTree.py", line 1333, in XML
    parser.feed(text)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 49, column 14

收到的页面部分如下:

    <script>
    jQuery(document).ready(function(){
    jQuery(window).scroll(function() {
        var scroll = jQuery(window).scrollTop();
        if (scroll >= 100) {
            jQuery(".t3-header").addClass("solid");
        }
        if (scroll <= 100) {
            jQuery(".t3-header").removeClass("solid");
        }
    });
    })
</script>

特别是第 49 行:

    if (scroll <= 100) {

所以问题出在左尖括号中,它似乎被处理为左标记符号。 我看到了几个类似的问题,但不明白如何处理这种情况。

最佳答案

您正在尝试使用 XML 解析器解析 HTML。请使用适当的工具(HTML 解析器):BeautifulSouplxml.html是最受欢迎的。

演示:

>>> from bs4 import BeautifulSoup
>>> import urllib.request
>>> 
>>> url = "http://rusdrama.com/afisha"
>>> response = urllib.request.urlopen(url)
>>>
>>> soup = BeautifulSoup(response, "html.parser")
>>> print(soup.title.get_text())
Афиша Харьковского академического русского драматического театра Пушкина

关于python - xml.etree.ElementTree.ParseError : not well-formed (invalid token) due to "<" symbol in script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40641664/

相关文章:

python - 如何从这个复杂而奇怪的 XML 中访问值? (子子子类)

c - 如何使用C从Xml中获取属性值

java - 创建自定义 JAXB 注释

Java:打开 Jar 内的 xml 文件。打不开

c# - 如何用 C# 编写解析器?

作为字典的 Python requests.json() 对象无法通过 hasattr() 或 object.keys() 调用中的值识别自己的键

python - 这个 'for m,n in matches' 是什么意思?

python - 基于一列的 MAX 值和有条件地另一列的 topN 值进行分组和过滤

python - 如何中止创建的协程Python

c++ - C++/C 中用于 Windows 的 XMLRPC