在 Python 中使用 BeautifulSoup 获取直接父标签 [英] Get immediate parent tag with BeautifulSoup in Python
本文介绍了在 Python 中使用 BeautifulSoup 获取直接父标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经研究过这个问题,但还没有看到解决这个问题的实际解决方案.我在 Python 中使用 BeautifulSoup,我想要做的是从页面中获取所有图像标签,遍历每个标签并检查每个标签以查看它的直接父标签是否是锚标签.
这是一些伪代码:
html = BeautifulSoup(responseHtml)对于 html.findAll('img') 中的图像:如果(image.parent.name == 'a'):image.hasParent = image.parent.link
对此有什么想法吗?
解决方案
for img in sound.find_all('img'):如果 img.parent.name == 'a':打印父母是一个链接"
演示:
<预><代码>>>>从 bs4 导入 BeautifulSoup>>>>>>数据 = """... <身体>... <a href="google.com"><img src="image.png"/></a>... </body>……">>>汤 = BeautifulSoup(数据)>>>img = 汤.img>>>>>>img.parent.name一个<小时>
您还可以使用 CSS 选择器:
soup.select('a > img')
I've researched this question but haven't seen an actual solution to solving this. I'm using BeautifulSoup with Python and what I'm looking to do is get all image tags from a page, loop through each and check each to see if it's immediate parent is an anchor tag.
Here's some pseudo code:
html = BeautifulSoup(responseHtml)
for image in html.findAll('img'):
if (image.parent.name == 'a'):
image.hasParent = image.parent.link
Any ideas on this?
解决方案
You need to check parent
's name
:
for img in soup.find_all('img'):
if img.parent.name == 'a':
print "Parent is a link"
Demo:
>>> 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
You can also retrieve the img
tags that have a direct a
parent using a CSS selector:
soup.select('a > img')
这篇关于在 Python 中使用 BeautifulSoup 获取直接父标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文