繁体   English   中英

如何从 bs4 的一个 p 标签上只抓取一个文本值

[英]How to scrape just one text value on one p tag from bs4

实际上该网站有一个<p>但里面有两个文本值,我只想抓取其中一个文本。 网址HTML如下:

<p class="text-base font-medium text-gray-700 w-1/2" xpath="1">
                        Great Clips

                                                    <br><span class="text-blue-600 font-normal text-sm">Request Info</span>
                                            </p>

在上面的 HTML 中,如果我们以<p>为目标,则有两个文本值(“Great Clips”和“Request Info”)。 我只想抓取“Great Clips”而不是两者,我将如何使用bs4来做到这一点?

您可以将.contents与索引一起使用以仅提取第一个孩子:

soup.p.contents[0].strip()

例子

from bs4 import BeautifulSoup

html = '''
<p class="text-base font-medium text-gray-700 w-1/2" xpath="1">
                        Great Clips

                                                    <br><span class="text-blue-600 font-normal text-sm">Request Info</span>
                                            </p>
'''
soup = BeautifulSoup(html)

soup.p.contents[0].strip()

Output

Great Clips

暂无
暂无

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

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