获取 html 中的所有链接,包括条件注释中的链接
Get all links in html including within conditional comments
假设我有这个简单的 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.html
或 BeautifulSoup
来获得两个链接?目前我只有一个。换句话说,我希望解析器也查看 html 条件注释(不确定技术术语是什么)。
lxml.html
>>> from lxml import html
>>> doc = html.fromstring(s)
>>> list(doc.iterlinks())
<<< [(<Element a at 0x10f7f7bf0>, 'href', 'http://link1.com', 0)]
BeautifulSoup
>>> from BeautifulSoup import BeautifulSoup
>>> b = BeautifulSoup(s)
>>> b.findAll('a')
<<< [<a href="http://link1.com">Link 1</a>]
需要提取注释然后进行解析。
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>]
假设我有这个简单的 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.html
或 BeautifulSoup
来获得两个链接?目前我只有一个。换句话说,我希望解析器也查看 html 条件注释(不确定技术术语是什么)。
lxml.html
>>> from lxml import html
>>> doc = html.fromstring(s)
>>> list(doc.iterlinks())
<<< [(<Element a at 0x10f7f7bf0>, 'href', 'http://link1.com', 0)]
BeautifulSoup
>>> from BeautifulSoup import BeautifulSoup
>>> b = BeautifulSoup(s)
>>> b.findAll('a')
<<< [<a href="http://link1.com">Link 1</a>]
需要提取注释然后进行解析。
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>]