python - beautifulsoup CSS Select - 查找其中不存在特定属性(ex 样式)的标签

标签 python css selector beautifulsoup

我第一次来这里。感谢您帮助我们菜鸟这么久。开门见山:

场景: 我正在开发一个现有程序,该程序正在将 CSS 选择器作为配置文件中的字符串读取,以使程序动态化并能够通过更改 CSS 选择器的配置值来废弃任何站点。

问题: 我正在尝试抓取一个将元素呈现为以下 2 个选项之一的网站:

选项 1:

.........
<div class="price">
  <span class="price" style="color:red;margin-right:0.1in">
    <del>$299</del>
  </span>
  <span class="price">
    $195
  </span> 
</div>

soup = soup.select("span.price") - this doesn't work as I need second span tag or last span tag :(

选项 2:

.........
<div class="price">
  <span class="price">
    $199
  </span>
</div>

soup = soup.select("span.price") - this works great!

问题: 在上述两个选项中,我希望能够获得最后一个跨度标签($195 或 $199),而不关心 $299。基本上我只想提取最终销售价格而不是原始价格。

所以目前我知道的两种方法是:

1) 始终获取最后一个 span 标签 2) 总是获取没有style属性的span标签

现在,我知道 not 运算符last-of-type 不存在于 bs4 中(只有 nth-of-type 是可用)所以我被困在这里。任何建议都是有帮助的。

编辑: - 由于这是一个现有程序,我不能使用 soup.find_all() 或除 soup.select() 之外的任何其他方法。对不起:(

谢谢!

最佳答案

可以搜索没有style属性的span标签:

prices = soup.select('span.price')
no_style = [price for price in prices if 'style' not in price.attrs]
>> [<span class="price">$199</span>]

关于python - beautifulsoup CSS Select - 查找其中不存在特定属性(ex 样式)的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225064/

相关文章:

python - 有没有办法隔离字符串的各个部分?

html - 如何居中导航栏元素?

html - 在本地浏览器上加载 HTML 和 CSS 文件

css - 不在某个元素内的样式链接

objective-c - 有没有办法打印 SEL Action ?

jquery - Javascript - Jquery,使用 'On' 方法(不是字符串)绑定(bind)动态选择器

python - Keras/Tensorflow 中不同时期的训练率如何变化

python - 如何使用pygtk打印图像

python - 我想以更好的结构打印输出

css - 子div隐藏父边框