当按值选择任何标记时,BeautifulSoup只返回标记的文本,希望返回完整标记

2024-06-25 06:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试根据标记的“string”值选择标记时,但没有指定特定的标记,我只得到返回的字符串值,而不是完整的标记。 如果我指定一个标签和一个字符串值,那么返回完整的标签

例如:

url = 'https://www.betts.com.au/item/39613-shifter.html?colour=black'
bs = BeautifulSoup(requests.get(url).text, features="html.parser")
print(bs.find_all(string='SHIFTER'))
print(bs.find_all('h1', string='SHIFTER'))

输出如下所示:

['SHIFTER', 'SHIFTER']
[<h1 class="wdj-item-descrpition-h1">SHIFTER</h1>]

我希望用第一个.find_all()得到完整的标签。我做错了,还是不可能

我一直在阅读docs here,它们没有完全相同的示例,但似乎建议find_all()应该产生一个标记,而不仅仅是文本-因此我有点困惑为什么只返回文本值


Tags: 字符串https标记文本urlstringbshtml
2条回答

使用bs.find_all(string='SHIFTER')看到的不是字符串(如str),而是bs4.element.NavigableString的实例,因此可以对它们使用标准的BeautifulSoup方法:

import requests
from bs4 import BeautifulSoup

url = 'https://www.betts.com.au/item/39613-shifter.html?colour=black'
bs = BeautifulSoup(requests.get(url).text, features="html.parser")

for text in bs.find_all(string='SHIFTER'):
    print(text.parent)

印刷品:

<span itemprop="name">SHIFTER</span>
<h1 class="wdj-item-descrpition-h1">SHIFTER</h1>

是的。这是预期的行为

你可以看到here

With string you can search for strings instead of tags.

相关问题 更多 >