我正在尝试解析网页以将其中的一些数据保存在 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 解析器):BeautifulSoup
或lxml.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/