【发布时间】:2016-11-09 14:20:53
【问题描述】:
我需要解析一个可能无效的 html 页面。实际上,其中很多是因为我从互联网上获得的。特别是,我需要获取一些标签的值。我可以通过正则表达式做到这一点,但我想它们不适合这项任务,尤其是因为 html 页面很大。
我的问题是,我应该选择什么库来解析这样的页面并获取我需要的标签/属性的值?
【问题讨论】:
标签: python html parsing web-scraping
我需要解析一个可能无效的 html 页面。实际上,其中很多是因为我从互联网上获得的。特别是,我需要获取一些标签的值。我可以通过正则表达式做到这一点,但我想它们不适合这项任务,尤其是因为 html 页面很大。
我的问题是,我应该选择什么库来解析这样的页面并获取我需要的标签/属性的值?
【问题讨论】:
标签: python html parsing web-scraping
试试 bs4 您可以通过
解析html文档from bs4 import BeautifulSoup
soup = BeautifulSoup(open("*.html","r").read(),"html.parser")
soup.title #return the node of title
print str(soup.title.string) #return the text in title
alist = soup.findAll('a') #return a list of all nodes of tag <a>
alist[0]['href'] #return the href attribute of this node as a str
blist = soup.findAll('div',{'class':'container'}) #return a list of all nodes of tag <div> whose class is container
更多信息请访问https://www.crummy.com/software/BeautifulSoup/bs4/doc/
【讨论】:
'html.parser' 之外的其他解析器。 lxml.html 或 html5lib。两者都可以解析无效的 HTML。前者更快,后者是用纯 Python 编写的,并且像现在大多数浏览器一样解释(损坏的)HTML。有关这些解析器以及如何安装它们的信息,请参阅 BeautifulSoup 的文档。
如果您真的对无效的 html 感到困扰,您可以将pre-processing 应用于提取的 html 以使其接近有效的 xml。看看如何:
import requests
import re
res = requests.get('http://page.com');
# remove everything before the `body` tag
res.text = re.sub(r"(.*?)<body>",'<body>', res.text )
# remove unneeded, long white spaces
res.text = re.sub(r"\s+",' ', res.text )
# make unclosed `p` tags closed
res.text = re.sub(r"<p>",'</p><p>', res.text )
# etc.
# here you start to parse your brushed-up code
【讨论】: