繁体   English   中英

美丽的汤4:提取没有标签的文本

[英]Beautiful soup 4: Extract text with no tags

<li class="actualPrice price fakeLink " data-automation="actual-price">
       <span class="visuallyhidden">Hello world</span>
Some text I want to extract
</li>

这是一些HTML。 我想提取文本“我想提取的某些文本”,并且我不想提取Hello world。

我尝试过像find('span')之类的东西,并使用next_sibling,但是我没有。

for a in soup.find_all('li', 'actualPrice'):
        print a.get_text()

这给了我Hello world和“一些我想提取的文字”。 是否有仅提取“我要提取的某些文本”的方法?

如果要在span标签之后提取下一个元素,则可以使用.next

>>> for a in soup.find_all('li', 'actualPrice'):
        print(a.span.next.next)
Some text I want to extract

只是为了另一种方法,您可以使用stripped_strings

for li in soup.find_all('li', 'actualPrice'):
    _, text_you_want = li.stripped_strings
    print (text_you_want)

输出:

我要提取的一些文字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM