【问题标题】:How to only select certain p tags without children?如何只选择没有孩子的某些 p 标签?
【发布时间】:2020-10-29 14:40:23
【问题描述】:

我是 beautifulSoup 的新手,当我想在大学课程网站上抓取一些信息时,我遇到了一个幼稚的问题。 html 如下所示,我想获取标签 p 之间的文本,而不是标签 p 之间的文本,标签 p 有一些孩子,例如<strong> and <em>

所需文字:本课程介绍......

非常感谢您的帮助!

<p>
<strong>MSDS 402 Introduction to Data Science</strong>
</p >
<p>This course introduces.....</p >
<p>
<em>Prerequisites: None.</em>
</p >
<p><a aria-label="MSDS 402-DL Section, ID#: 4765" class="link-list" href=" ">View MSDS 402-DL Sections</a ></p >

【问题讨论】:

标签: python html beautifulsoup


【解决方案1】:

您可以使用 CSS 选择器 p:not(:has(*)) 来选择标签 &lt;p&gt; 而没有任何子标签。

例如:

from bs4 import BeautifulSoup


txt = '''<p>
<strong>MSDS 402 Introduction to Data Science</strong>
</p >
<p>This course introduces.....</p >
<p>
<em>Prerequisites: None.</em>
</p >
<p><a aria-label="MSDS 402-DL Section, ID#: 4765" class="link-list" href=" ">View MSDS 402-DL Sections</a ></p >'''


soup = BeautifulSoup(txt, 'html.parser')

for p in soup.select('p:not(:has(*))'):
    print(p)

打印:

<p>This course introduces.....</p>

【讨论】:

  • 您好安德烈,感谢您的回答!虽然我对 css 不熟悉,但是这个方法行得通!谢谢!!
猜你喜欢
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 2014-12-04
  • 2012-10-13
  • 2011-10-05
相关资源
最近更新 更多