从html页面中提取特定内容

2024-05-17 05:45:09 发布

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

假设我有一个html页面源代码,如:

<p><font face="Arial" color="#400040"><small><strong>

<a href="some_link">description</a>: </strong>some text.</small></font></p>

我只想提取“描述”部分? 我该怎么做。我认为有一个非常python的方法来做到这一点。 谢谢


Tags: 方法text源代码htmllinksome页面description
3条回答

您可以使用BeautifulSoup,请参见docs中的示例:

from bs4 import BeautifulSoup
html_doc = '''<p><font face="Arial" color="#400040"><small><strong>

<a href="some_link">description</a>: </strong>some text.</small></font></p>
'''
soup = BeautifulSoup(html_doc)
for link in soup.find_all('a'):
    print(link.get('href'))

使用Beautifulsoup。你知道吗

>>> from BeautifulSoup import BeautifulSoup
>>> html = '<p><font face="Arial" color="#400040"><small><strong><a href="some_link">description</a>: </strong>some text.</small></font></p>'
>>> soup = BeautifulSoup(html)
>>> soup.find('a', text=True)
u'description'

如果您有多个标记(很可能是这样),您可以执行以下操作:

>>> for link in soup.findAll('a'):
...     print link.text

获取BeautifulSoup。然后:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(your_text)
description = soup.find('a').string

您可能需要修改最后一行以唯一地标识a标记。你知道吗

相关问题 更多 >