Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取特定div中的文本避免通过BS4从嵌套div中获取文本_Python_Html_Python 3.x_Beautifulsoup - Fatal编程技术网

Python 如何获取特定div中的文本避免通过BS4从嵌套div中获取文本

Python 如何获取特定div中的文本避免通过BS4从嵌套div中获取文本,python,html,python-3.x,beautifulsoup,Python,Html,Python 3.x,Beautifulsoup,结构看起来像这样 一些文本 一些文本 98 使用findAll()然后使用以下参数: string=True-仅搜索字符串 recursive=False-不要查看孩子们 从bs4导入美化组 soup=BeautifulSoup(“some text some text98”、“html.parser”) soup.div.findAll(string=True,recursive=False)[-1] >>> '98' 尝试使用div:n子元素(2)获取下一个div,使用在元素之间导航 范

结构看起来像这样


一些文本
一些文本
98
使用
findAll()
然后使用以下参数:

string=True
-仅搜索字符串
recursive=False
-不要查看孩子们

从bs4导入美化组
soup=BeautifulSoup(“some text some text98”、“html.parser”)
soup.div.findAll(string=True,recursive=False)[-1]
>>> '98'
尝试使用
div:n子元素(2)
获取下一个
div
,使用在元素之间导航

范例

从bs4导入美化组
html=”“”
一些文本1
一些文本2
98
"""
page_soup=BeautifulSoup(html,“html.parser”)
打印(第\u页。选择(“div:n个孩子(2)”)[0]。下一个兄弟姐妹)


打印出
98

试着看看这个:伙计,这确实是我需要的,但我不明白为什么它不能与我的代码一起工作。我已将其添加到我的问题中,请帮助,谢谢!问题是代码中有一个更高的空格,因此我得到了空格。我的代码的完整决定如下所示:number=social.div.findAll(string=True,recursive=False)[1]。replace('\n','')
from bs4 import BeautifulSoup

html = """
<div>
  <div>some text 1</div>
  <div>some text 2</div>
  98
</div>
"""

page_soup = BeautifulSoup(html, "html.parser")
print(page_soup.select("div:nth-child(2)")[0].next_sibling)