Python HTMLPasser和奇怪的行为
我必须使用Python 3从以下网页中提取信息:Python HTMLPasser和奇怪的行为,python,html,html-parsing,Python,Html,Html Parsing,我必须使用Python 3从以下网页中提取信息: 使用URLLIB请求的下载似乎是正确的,但令人惊讶的是,当我用HTMLPARSER类解析HTML文件时,解析似乎停止在Meta标签的中间,没有给出任何理由。 这是我的代码: import urllib.request from html.parser import HTMLParser def downloadLIBOR(): html_file = urllib.request.urlopen("http://www.homefina
使用URLLIB请求的下载似乎是正确的,但令人惊讶的是,当我用HTMLPARSER类解析HTML文件时,解析似乎停止在Meta标签的中间,没有给出任何理由。 这是我的代码:
import urllib.request
from html.parser import HTMLParser
def downloadLIBOR():
html_file = urllib.request.urlopen("http://www.homefinance.nl/english/international-interest-rates/libor/libor-interest-rates-gbp.asp")
return html_file
class tmpHTMLParser(HTMLParser):
def __init__(self):
self._libor = "0.81625 %"
self._stack = []
self._properStack = []
super().__init__()
def handle_starttag(self, tag, attrs):
print("starttag " + str(tag))
print(self.get_starttag_text())
self._stack.append(tag)
def handle_startendtag(self, tag, attrs):
print("startendtag")
def unknown_decl(self, data):
print("unknown_decl")
def handle_endtag(self, tag):
print("endtag " + str(tag))
self._stack.pop()
def _buildProperStack(webpage):
"""dev tool: return the stack leading to the libor rate libor into the webpage webpage."""
parser = tmpHTMLParser()
parser.feed(webpage)
if __name__ == "__main__":
webpage = downloadLIBOR()
print("download done")
html = str(webpage.read())
_buildProperStack(html)
exit(0)
不确定您实际想做什么,但使用BeautifulSoup解析HTML更方便、更简单,也更不容易出错。顺便说一句,我注意到您忘记在parser.feed()之后执行parser.close()。它可能正在缓冲某些内容,关闭将迫使它完成。我将查看BeautifulSoup。你可以忽略我的代码的一部分,但是如果你运行它,你将在无处可见解析停止。顺便说一句,我使用的是Python3。您的代码将在其他html输入上运行到完成,因此该文件中有一些东西是解析器无法处理的。(我认为它被嵌入的javascript扼住了。)@Steven D.Majewski这个HTMLPasser是跛脚的,因为它可以因为javascript而停止解析!?