2012-05-14 153 views
0

假设我有一个像HTML网页的源文件:?提取HTML页面的特定内容

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

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

我想只提取“描述部分 如何做到这一点,我认为有一个很pythonic的方法如果你有多个标签,这很可能将是做到这一点。 感谢

回答

2

获取BeautifulSoup。然后:

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

您可能需要修改最后一行以唯一标识您的标签。

1

使用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 
2

您可以使用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'))