使用Python解析HTML

2024-04-25 16:38:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个用于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的“Inspect element”特性(查看HTML),您就会知道它会像树一样以良好的嵌套方式提供所有标记。

我更喜欢一个内置模块,但这可能要求太高了。


我在互联网上浏览了很多关于堆栈溢出和一些博客的问题,其中大多数都建议美化loup、lxml或HTMLParser,但很少有人详细介绍功能,最后只是讨论哪个更快/更高效。


Tags: 模块标记文本divid解析器内容列表
3条回答

在这里,您可以阅读更多关于Python中不同HTML解析器及其性能的信息。尽管这篇文章有点过时了,但它还是给了你一个很好的概述。

Python HTML parser performance

即使不是内置的,我还是推荐美容师组。只是因为这样做很容易。例如:

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

我想你要找的是pyquery

pyquery: a jquery-like library for 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的inspect元素相同的选择器。例如:

the element selector is 'div#mw-head.noprint'

被检查的元件选择器是“div#mw head.noprint”。所以在pyquery中,只需要传递这个选择器:

pq('div#mw-head.noprint')

So that I can ask it to get me the content/text in the div tag with class='container' contained within the body tag, Or something similar.

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)

我想你不需要性能描述-只要看看美组是如何工作的。看看它的official documentation

相关问题 更多 >