Python 基于Beautifulsoup中的内容排除标记

Python 基于Beautifulsoup中的内容排除标记,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我正在抓取类似于以下内容的html数据: <div class="target-content"> <p id="random1"> "the content of the p" </p> <p id="random2"> "the content of the p" </p> <p> <q class="semi-predictable"

我正在抓取类似于以下内容的html数据:

<div class="target-content">
    <p id="random1">
      "the content of the p"
    </p>

    <p id="random2">
      "the content of the p"
    </p>

    <p>
      <q class="semi-predictable">
         "q tag content that I don't want
      </q>
    </p>

    <p id="random3">
      "the content of the p"
    </p>

</div>
我的问题是,在我找到所有
标记的结果集之后,如何筛选出包含
的单个
及其内容

注意:在从
soup.find('div',class='target-content')find_all('p')
获取结果集后,我将以以下方式将结果集中的每个
迭代添加到列表中:

content = ''
    for p in contentlist:
        content += str(p)

您只需跳过
p
内有
q
标记的标记:

for p in soup.select('div.target-content > p'):
    if p.q:  # if q is present - skip
        continue
    print(p)

其中
p.q
是指向
p.find(“q”)
的快捷方式
div.target-content>p
是一个将
p
标记与
div
元素的直接子元素与
目标内容
类相匹配的标记。

您可以使用
过滤器
来完成以下操作:

filter(lambda e: e.find('q') == None, soup.find('div', class_='target-content').find_all('p'))

谢谢,这正是我想要理解的。谢谢你的解释;我不认为在Beautifulsoup中应该经常使用CSS选择器。谢谢你的帮助,我最终使用了上面@Alexe答案的变体,尽管你的答案也很有用。
filter(lambda e: e.find('q') == None, soup.find('div', class_='target-content').find_all('p'))