使用beauthoulsoup搜索标记内的文本,并在i之后返回标记中的文本

2024-09-30 22:20:10 发布

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

我试图用漂亮的soup解析python中的以下HTML代码。我希望能够搜索标签内的文本,例如“Color”并返回下一个标签“Slate,mykonos”的文本,然后对下一个标签这样做,这样对于一个给定的文本类别,我可以返回它的相应信息。在

但是,我发现很难找到合适的代码来实现这一点。在

<h2>Details</h2>
<div class="section-inner">
    <div class="_UCu">
        <h3 class="_mEu">General</h3>
        <div class="_JDu">
            <span class="_IDu">Color</span>
            <span class="_KDu">Slate, mykonos</span>
        </div>
    </div>
    <div class="_UCu">
        <h3 class="_mEu">Carrying Case</h3>
        <div class="_JDu">
            <span class="_IDu">Type</span>
            <span class="_KDu">Protective cover</span>
        </div>
        <div class="_JDu">
            <span class="_IDu">Recommended Use</span>
            <span class="_KDu">For cell phone</span>
        </div>
        <div class="_JDu">
            <span class="_IDu">Protection</span>
            <span class="_KDu">Impact protection</span>
        </div>
        <div class="_JDu">
            <span class="_IDu">Cover Type</span>
            <span class="_KDu">Back cover</span>
        </div>
        <div class="_JDu">
            <span class="_IDu">Features</span>
            <span class="_KDu">Camera lens cutout, hard shell, rubberized, port cut-outs, raised edges</span>
        </div>
    </div>

我使用以下代码检索我的div标记

^{pr2}$

一旦我检索到标记,我就可以在其中导航,但我找不到正确的代码,使我能够找到一个标记内的文本,并在标记之后返回该标记中的文本。在

任何帮助都会非常感谢,因为我是python新手,而且我已经走到了死胡同。在


Tags: 代码标记文本div标签h2h3class
2条回答

试试看。它还可以为您提供相应的值。请确保将html elements括在content=""" """变量内,并用三个引号括起来,看看它是如何工作的。在

from bs4 import BeautifulSoup

soup = BeautifulSoup(content,"lxml")
for elem in soup.select("._JDu"):
    item = elem.select_one("span")
    if "Features" in item.text:  #try to see if it misses the corresponding values
        val = item.find_next("span").text
        print(val)

您可以定义一个函数来返回您输入的键的值:

def get_txt(soup, key):
    key_tag = soup.find('span', text=key).parent
    return key_tag.find_all('span')[1].text

color = get_txt(soup, 'Color')
print('Color: ' + color)
features = get_txt(soup, 'Features')
print('Features: ' + features)

输出:

^{pr2}$

我希望这就是你要找的。在

说明:

soup.find('span', text=key)返回<span>标记,其text=key。在

.parent返回当前<span>标记的父标记。在

示例:

key='Color'时,soup.find('span', text=key).parent将返回

<div class="_JDu">
    <span class="_IDu">Color</span>
    <span class="_KDu">Slate, mykonos</span>
</div>

现在我们把它存储在key_tag。只剩下第二个<span>的文本,这是key_tag.find_all('span')[1].text行所做的。在

相关问题 更多 >