python - 获取 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.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)]
美丽汤
>>> 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>]
推荐阅读
- linux - 无法将双浮点模块与软浮点模块 riscv 编译器链接
- r - 一次调整所有变量的数据帧滞后
- ios - 如何在 SwiftUI 中将包含列表的视图的背景颜色更改回白色
- ansible - 是否可以从剧本中的动态清单中解析加密的 Ansible 保险库值?
- postgresql - Pgadmin 容器在使用 docker-compose 时会杀死 postgres
- html - 查找或生成正确的文件扩展名
- python - Python——反射式地初始化类
- spring - Mule Migration 从 3.8.4 到 3.9.2 jars 相关问题
- html - 当屏幕变小时,如何使导航栏堆栈上的元素相互叠加?
- java - 如果用户没有输入数字,如何在输入部分插入 NumberFormatException 并显示“输入错误”