0

假设我有以下 HTML 片段:

<p class="toSelect">
    "some text here..."
    <br>
    "Other text here..."
</p>

关于如何在 Python 中使用 Beautifulsoup获取<p>标签及其子标签之间的第一个文本的任何建议?<br>

4

2 回答 2

1

您可以使用.contents获取<p>所有文本和子项,<p>并从列表中选择第一项。

from bs4 import BeautifulSoup

s = '''<p class="toSelect">
    "some text here..."
    <br>
    "Other text here..."
</p>'''

soup = BeautifulSoup(s, 'html.parser')
x = soup.find('p')
print(x.contents[0].strip())
Output:

"some text here..."

您可以阅读更多关于.contents-文档

于 2021-07-03T12:25:10.247 回答
1

您可以选择元素<p class="toSelect">,然后.find_next使用text=True

from bs4 import BeautifulSoup


html_doc = """
<p class="toSelect">
    "some text here..."
    <br>
    "Other text here..."
</p>"""


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

text = soup.select_one(".toSelect").find_next(text=True)
print(text)

印刷:


    "some text here..."

于 2021-07-03T14:17:57.067 回答