在带有BeautifulSoup的ContentPane中查找没有标记的文本

2024-04-19 22:05:56 发布

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

我的问题类似于:Get HTML Text that has no tagBeautiful Soup - Print a containers text without printing the text of the child elements

如何从ContentPane获取此文本:Updated September 11, 2018 (57) Cases + (1) traffic w/contributing heroin?你知道吗

HTML:

<!--Container Content-->
<div class="contentmain">
    <div id="dnn_ctr3799_ContentPane" class="contentpane">
        <!--Start_Module_3799-->
        Updated September 11, 2018 (57) Cases + (1) traffic w/contributing heroin

尝试1soup.find

我可以使用soup.find打印整个ContentPane,包括上面的文本,但我不想全部打印出来:

name_box = soup.find(id= 'dnn_ctr3799_ContentPane')
name = name_box.text.strip()
print name

尝试2nextSibling

我试过nextSibling,但没有结果。你知道吗

texts = soup.findAll("div", {"id":"dnn_ctr3799_ContentPane"})
for text in texts:
    if text.string:
        if "dnn_ctr3799_ContentPane" in text.string:
            print text.nextSibling.string.strip()

网页链接:2018 Heroin/Fentanyl Overdose Deaths


Tags: thetextname文本dividstringhtml
1条回答
网友
1楼 · 发布于 2024-04-19 22:05:56

我和一个很强的容器打交道。我想要的字符串是父项<div id="dnn_ctr3799_ContentPane" class="contentpane">下的字符串<! Start_Module_3799 >sibling

回答:

texts = soup.find('div', id='dnn_ctr3799_ContentPane')
name = texts.find_next(string=True)
print od.nextSibling.string

相关问题 更多 >