首页 > 解决方案 > 获取 html 中的所有链接,包括条件注释中的链接

问题描述

假设我有这个简单的 html:

<html>
  <body>

    <!--[if !mso]><!-->
    <a href="http://link1.com">Link 1</a>
    <!--<![endif]-->

    <!--[if mso]>
      <a href="http://link2.com">Link 2</a>
    <![endif]-->

  </body>
</html>

有没有办法使用lxml.htmlBeautifulSoup获取两个链接?目前我只得到一个。换句话说,我希望解析器也查看 html 条件注释(不确定技术术语是什么)。

lxml.html

>>> from lxml import html
>>> doc = html.fromstring(s)
>>> list(doc.iterlinks())

<<< [(<Element a at 0x10f7f7bf0>, 'href', 'http://link1.com', 0)]

美丽汤

>>> from BeautifulSoup import BeautifulSoup
>>> b = BeautifulSoup(s)
>>> b.findAll('a')

<<< [<a href="http://link1.com">Link 1</a>]

标签: pythonbeautifulsouplxml

解决方案


需要提取评论然后解析它们。

html = '''<html>
  <body>

    <!--[if !mso]><!-->
    <a href="http://link1.com">Link 1</a>
    <!--<![endif]-->

    <!--[if mso]>
      <a href="http://link2.com">Link 2</a>
    <![endif]-->

  </body>
</html>'''



from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all('a', href=True)

comments = soup.find_all(string=lambda text: isinstance(text, Comment))
for comment in comments:
    if BeautifulSoup(comment).find_all('a', href=True):
        links += BeautifulSoup(comment).find_all('a', href=True)

print (links)

输出:

[<a href="http://link1.com">Link 1</a>, <a href="http://link2.com">Link 2</a>]

推荐阅读