查找包含给定文本的未知标签
Find unknown tag containing given text
我的 HTML 就像:
<body>
<div class="afds">
<span class="dfsdf">mytext</span>
</div>
<div class="sdf dzf">
<h1>some random text</h1>
</div>
</body>
我想找到所有包含“text”及其对应的 类 的标签。在这种情况下,我想要:
- 跨度,“dfsdf”
- h1, 空
接下来,我希望能够浏览返回的标签。例如,找到 div 父标签和所有返回标签的相应 类。
如果我执行以下
soupx.find_all(text=re.compile(".*text.*"))
它只是 returns 标签的文本部分:
['mytext', ' some random text']
请帮忙。
find_all() 不 return 只是字符串,它 return 是 bs4.element.NavigableString。
这意味着您可以根据这些结果调用其他 beautifulsoup 函数。
看看 find_parent 和 find_parents: documentation
childs = soupx.find_all(text=re.compile(".*text.*"))
for c in childs:
c.find_parent("div")
您可能正在寻找以下内容:
ts = soup.find_all(text=re.compile(".*text.*"))
for t in ts:
if len(t.parent.attrs)>0:
for k in t.parent.attrs.keys():
print(t.parent.name,t.parent.attrs[k][0])
else:
print(t.parent.name,"null")
输出:
span dfsdf
h1 null
我的 HTML 就像:
<body>
<div class="afds">
<span class="dfsdf">mytext</span>
</div>
<div class="sdf dzf">
<h1>some random text</h1>
</div>
</body>
我想找到所有包含“text”及其对应的 类 的标签。在这种情况下,我想要:
- 跨度,“dfsdf”
- h1, 空
接下来,我希望能够浏览返回的标签。例如,找到 div 父标签和所有返回标签的相应 类。
如果我执行以下
soupx.find_all(text=re.compile(".*text.*"))
它只是 returns 标签的文本部分:
['mytext', ' some random text']
请帮忙。
find_all() 不 return 只是字符串,它 return 是 bs4.element.NavigableString。 这意味着您可以根据这些结果调用其他 beautifulsoup 函数。
看看 find_parent 和 find_parents: documentation
childs = soupx.find_all(text=re.compile(".*text.*"))
for c in childs:
c.find_parent("div")
您可能正在寻找以下内容:
ts = soup.find_all(text=re.compile(".*text.*"))
for t in ts:
if len(t.parent.attrs)>0:
for k in t.parent.attrs.keys():
print(t.parent.name,t.parent.attrs[k][0])
else:
print(t.parent.name,"null")
输出:
span dfsdf
h1 null