微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Selenium xpath all(// *)不接受每个css元素

我正在尝试使用selenium(XPath)列出不同网站上的每种颜色,我不知道为什么我的脚本不能全部获取它们.

background_ele = browser.find_elements_by_xpath("//*[contains(@style,'background')]")
colors_ele = browser.find_elements_by_xpath("//*[contains(@style,'color')]")
background_colors = [x.value_of_css_property('background-color') for x in background_ele]
colors = [x.value_of_css_property('background-color') for x in colors_ele]

代码应该获得具有背景或颜色属性的每个元素,但是当我为此网站运行它时:“www.example.com”我看不到下面的颜色显示在页脚和标题上:

background-color: rgb(54, 64, 66) !important;

我只打印那些:

['rgba(255, 255, 255, 0)', 'rgba(0, 0, 0, 0)', 'rgba(169, 68, 66, 1)', 'rgba(0, 0, 0, 0)']

我的代码是否存在问题,或者使用selenium可能是一种更有效的方法

更新

我的脚本实际上只接受html中的标记而不是css文件中的标记.

<div class="example"style="src="https://example.com/img/slider.jpg"></div>

如何使用selenium来定位包含参数“background”或“color”的每个css属性(来自css文件)?

解决方法:

Selenium不处理DOM结构中缺少的CSS属性.或者,您可以通过为每个所需节点应用一个类来使用jQuery.filter(),该类允许以标准方式查找元素:
我下面的例子是// div [contains(@class,’found’)]

$(document).ready(function() {
	$("*").filter(function() {
		return $(this).css("background-color") == "rgb(54, 64, 66)";
	}).text("true").addClass("found"); 
});
.white {
background-color: rgb(255, 255, 255);
}
.black {
background-color: rgba(0, 0, 0, 0);
}
.carmine {
background-color: rgba(169, 68, 66, 1);
}
.cosmos {
background-color: rgb(54, 64, 66);
}
.found {
color: green !important;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="white">false</div>
<div class="black">false</div>
<div class="carmine">false</div>
<div class="cosmos">false</div>

原文地址:https://codeday.me/bug/20190710/1424889.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐