使用python在HTML代码中查找特定注释

geo*_*ano 2 python

我无法在python中找到具体的注释,例如<!-- why -->.我的主要原因是找到2条具体评论中的所有链接.像解析器一样的东西.我试过这个Beautifulsoup:

import urllib
over=urlopen("www.gamespot.com").read()
soup = BeautifulSoup(over)
print soup.find("<!--why-->")
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我想我可能不得不使用regex而不是Beautifulsoup.

请帮忙.

示例:我们有像这样的HTML代码

<!--why-->
www.godaddy.com
<p> nice one</p>
www.wwf.com
<!-- why not-->
Run Code Online (Sandbox Code Playgroud)

编辑:在2条评论之间,可能存在其他东西,如标签.

我需要存储所有链接.

DSM*_*DSM 6

如果你想要所有的评论,你可以使用findAll一个可调用的:

>>> from bs4 import BeautifulSoup, Comment
>>> 
>>> s = """
... <p>header</p>
... <!-- why -->
... www.test1.com
... www.test2.org
... <!-- why not -->
... <p>tail</p>
... """
>>> 
>>> soup = BeautifulSoup(s)
>>> comments = soup.findAll(text = lambda text: isinstance(text, Comment))
>>> 
>>> comments
[u' why ', u' why not ']
Run Code Online (Sandbox Code Playgroud)

一旦你得到它们,你可以使用通常的技巧来移动:

>>> comments[0].next
u'\nwww.test1.com\nwww.test2.org\n'
>>> comments[0].next.split()
[u'www.test1.com', u'www.test2.org']
Run Code Online (Sandbox Code Playgroud)

根据页面的实际情况,您可能需要稍微调整一下,然后您必须选择所需的注释,但这应该可以帮助您入门.

编辑:

如果你真的只想要看起来像某些特定文本的那些,你可以做类似的事情

>>> comments = soup.findAll(text = lambda text: isinstance(text, Comment) and text.strip() == 'why')
>>> comments
[u' why ']
Run Code Online (Sandbox Code Playgroud)

或者您可以使用列表解析在事后过滤它们:

>>> [c for c in comments if c.strip().startswith("why")]
[u' why ', u' why not ']
Run Code Online (Sandbox Code Playgroud)