stw*_*ite 14 html python beautifulsoup html-parsing
我已经研究过这个问题,但还没有看到解决这个问题的实际解决方案.我正在使用带有Python的BeautifulSoup,我正在寻找的是从页面获取所有图像标记,循环遍历每个标记并检查每个标记以查看它的直接父标记是否为锚标记.
这是一些伪代码:
html = BeautifulSoup(responseHtml)
for image in html.findAll('img'):
if (image.parent.name == 'a'):
image.hasParent = image.parent.link
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
ale*_*cxe 20
for img in soup.find_all('img'):
if img.parent.name == 'a':
print "Parent is a link"
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from bs4 import BeautifulSoup
>>>
>>> data = """
... <body>
... <a href="google.com"><img src="image.png"/></a>
... </body>
... """
>>> soup = BeautifulSoup(data)
>>> img = soup.img
>>>
>>> img.parent.name
a
Run Code Online (Sandbox Code Playgroud)
您还可以使用CSS选择器检索img具有直接a父级的标记:
soup.select('a > img')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15285 次 |
| 最近记录: |