【问题标题】:css selector select only the first child text and not the divcss 选择器只选择第一个子文本而不是 div
【发布时间】:2020-09-17 07:14:12
【问题描述】:

我想使用 css 选择器从该 div<div class="one"> 中仅选择文本(在我的示例中为“1.42”)用于抓取目的:

<div class="one">
1.42
<div class="nested">..</div>
</div>

我试过这个但返回整个&lt;div class="one"&gt;(我只想要文本):

div.one:first-child

还有这个:

div.one:first-child:not(.nested)

他们都返回文本加上div.nested里面的内容

编辑:

我想通过 Beautifulsoup 使用选择器来抓取特定的文本

soup.select_one('div.one:first-child:not(.nested)')

【问题讨论】:

  • 您想对该文本做什么?隐藏它?
  • 不能和 Beautifulsoup 一起使用来抓取
  • 我看到我在下面的回答没有考虑到您可能无法编辑外部 html 文件,所以如果您能澄清您的 soup.select_one 测试给出的结果是什么有帮助。编辑:你已经写了它是什么,对此感到抱歉。那时我怕是无能为力。 Beautifulsoup 中是否可以使用函数从结果中剥离整个内部 div.nested?

标签: javascript html css web-scraping


【解决方案1】:

无论有没有 css 类,您都不能对不在 html 标记内的内容进行 css 选择。在您的情况下,您应该将 1.42 文本包装在 html 标记中,例如 &lt;p&gt;

这也是最佳实践,永远不要直接在 div 中打印文本,没有像 p 这样的语义文本标签。

拥有&lt;p class="..."&gt;Text here&lt;/p&gt; 后,您可以选择 div:first-child 或直接选择 p 或 p.theclassname。另一种方法是div:nth-child(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2021-10-30
    • 2011-01-06
    • 1970-01-01
    • 2012-06-24
    相关资源
    最近更新 更多