python - 如何获取beautifulsoup中所选标签的下一个标签(元素)

标签 python python-3.x beautifulsoup

我想要一个只有 HTML 标签,没有任何唯一标识的元素 但我可以选择该标签的上标签,如何从该选择中获取下一个标签 (例如)

<div>
    <span class="class1"> text </span>
    <p> I want this text </P> <!-- how to get this text --> 
</div>

我尝试过的代码

data = BeautifulSoup("""
    <div>
        <span class="class1"> text </span>
        <p> I want this text </P> <!-- how to get this text -->
    </div>
    """, 'lxml')

data.find('span', class_='class1').next_sibling
data.find('span', class_='class1').next_element

输出:

'\n'
' text '

最佳答案

尝试.find_next_sibling() :

data.find('span', class_='class1').find_next_sibling()

如果您想从 NavigableString 对象中提取文本,请使用 .text

关于python - 如何获取beautifulsoup中所选标签的下一个标签(元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54264315/

相关文章:

python - 决策树生成具有相同类的终端叶

python - Google App Engine 数据库模型对象对象不可迭代错误

python - 是什么阻止我的异步代码运行异步?

Python 2 与 3 原始字节输出

python - 如何在 splinter 中选择 class , div , tag ?

python - BeautifulSoup 错误地解析页面并且找不到链接

python - 不寻常的列表推导执行顺序

python - 如何获取匹配的字符串

ios - Python 3 错误 : ImportError: No module named selenium

python - 用BeautifulSoup抓取: want to scrape entire column including header and title rows