我第一次来这里。感谢您帮助我们菜鸟这么久。开门见山:
场景: 我正在开发一个现有程序,该程序正在将 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/