Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.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 从不带子元素的内部元素获取文本_Python_Python 3.x_Web Scraping_Beautifulsoup - Fatal编程技术网

Python 从不带子元素的内部元素获取文本

Python 从不带子元素的内部元素获取文本,python,python-3.x,web-scraping,beautifulsoup,Python,Python 3.x,Web Scraping,Beautifulsoup,我正在抓取一个包含多个p元素的网页,我想在不包含他们的孩子的情况下获取其中的文本 页面的结构如下所示: <p class="default"> <div>I don't want this text</div> I want this text </p> 我正在将Beautifulsoup4与Python 3一起使用 编辑:当我使用 parent.find_all("p", {"c

我正在抓取一个包含多个
p
元素的网页,我想在不包含他们的孩子的情况下获取其中的文本

页面的结构如下所示:

<p class="default">
    <div>I don't want this text</div>
    I want this text
</p>
我正在将Beautifulsoup4与Python 3一起使用

编辑:当我使用

parent.find_all("p", {"class": "public item-cost"}, text=True, recursive=False)

它返回一个空列表

您可以使用
.find_next_sibling()
text=True
参数:

from bs4 import BeautifulSoup

html_doc = """
<p class="default">
    <div>I don't want this text</div>
    I want this text
</p>
"""

soup = BeautifulSoup(html_doc, "html.parser")

print(soup.select_one(".default > div").find_next_sibling(text=True))

或使用
.contents

print(soup.find("p", class_="default").contents[-1])

编辑:要删除字符串,请执行以下操作:

print(soup.find("p", class_="default").contents[-1].strip())

您可以使用xpath,它有点复杂,但提供了非常强大的查询功能

像这样的东西对你有用:

soup.xpath('//p[contains(@class,“default”)]///text()[normalize-space()

您有两个打开的
标记。这就是你真正拥有的吗?对不起,错别字。已修复。内容[-1]应该是有效的,谢谢。
print(soup.find("p", class_="default").contents[-1])
print(soup.find("p", class_="default").contents[-1].strip())