使用 Python 解析 HTML
- 2024-12-04 08:56:00
- admin 原创
- 136
问题描述:
我正在寻找一个 Python 的 HTML 解析器模块,它可以帮助我以 Python 列表/字典/对象的形式获取标签。
如果我有以下形式的文件:
<html>
<head>Heading</head>
<body attr1='val1'>
<div class='container'>
<div id='class'>Something here</div>
<div>Something else</div>
</div>
</body>
</html>
然后它应该给我一种通过 HTML 标签的名称或 id 访问嵌套标签的方法,这样我基本上就可以要求它获取标签中div
包含class='container'
的body
标签内的内容/文本,或类似的东西。
如果您使用过 Firefox 的“检查元素”功能(查看 HTML),您就会知道它会以像树一样嵌套的方式为您提供所有标签。
我更喜欢内置模块,但这可能要求有点太多了。
我浏览了 Stack Overflow 上的大量问题以及互联网上的一些博客,大多数都建议使用 BeautifulSoup、lxml 或 HTMLParser,但很少有人详细介绍其功能,而只是简单地争论哪一个更快/更高效。
解决方案 1:
这样我就可以要求它获取 body 标签内包含的 class='container' 的 div 标签中的内容/文本,或者类似的东西。
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
html = #the HTML code you've written above
parsed_html = BeautifulSoup(html)
print(parsed_html.body.find('div', attrs={'class':'container'}).text)
我想你不需要性能描述 - 只需阅读 BeautifulSoup 的工作原理。查看其官方文档。
解决方案 2:
我猜你要找的是pyquery:
pyquery:一个类似于 jquery 的 Python 库。
您想要的一个例子可能是这样的:
from pyquery import PyQuery
html = # Your HTML CODE
pq = PyQuery(html)
tag = pq('div#id') # or tag = pq('div.class')
print tag.text()
它使用与 Firefox 或 Chrome 的检查元素相同的选择器。例如:
检查的元素选择器是 'div#mw-head.noprint'。因此在 pyquery 中,您只需传递此选择器:
pq('div#mw-head.noprint')
解决方案 3:
您可以在此处阅读有关 Python 中不同 HTML 解析器及其性能的更多信息。尽管这篇文章有点过时,但它仍然为您提供了一个很好的概述。
Python HTML 解析器性能
尽管 BeautifulSoup 不是内置的,但我还是推荐它。因为它可以很轻松地完成这类任务。例如:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)
x = soup.body.find('div', attrs={'class' : 'container'}).text
解决方案 4:
与其他解析器库相比,lxml
速度极快:
http://blog.dispatched.ch/2010/08/16/beautifulsoup-vs-lxml-performance/
http://www.ianbicking.org/blog/2008/03/python-html-parser-performance.html
而且使用cssselect
它来抓取 HTML 页面也相当容易:
from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
print '%s: %s' % (div.text_content(), div.get('href'))
lxml.html 文档
解决方案 5:
我推荐使用lxml来解析 HTML。请参阅“解析 HTML”(在 lxml 网站上)。
根据我的经验,Beautiful Soup 会搞乱一些复杂的 HTML。我认为这是因为 Beautiful Soup 不是一个解析器,而是一个非常好的字符串分析器。
解决方案 6:
我建议使用justext库:
https://github.com/miso-belica/jusText
用法:
Python2:
import requests
import justext
response = requests.get("http://planet.python.org/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
print paragraph.text
Python3:
import requests
import justext
response = requests.get("http://bbc.com/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
print (paragraph.text)
解决方案 7:
我会使用 EHP
这里是:
from ehp import *
doc = '''<html>
<head>Heading</head>
<body attr1='val1'>
<div class='container'>
<div id='class'>Something here</div>
<div>Something else</div>
</div>
</body>
</html>
'''
html = Html()
dom = html.feed(doc)
for ind in dom.find('div', ('class', 'container')):
print ind.text()
输出:
Something here
Something else