我目前正在使用 Selenium 和 PhantomJS 以及 Python 来抓取呈现的网页。检查 HTML 内容中是否存在某些单词很容易(例如 if "example"in html
...),但我有兴趣在页面中搜索包含 CSS 属性的元素大于或等于某物的值。
例如,理想的做法是抓取网站列表并保存具有 CSS 的页面,从而为元素的 z-index 提供异常大的值。除了渲染页面的 CSS 爬网功能外,一切都已构建。有人对解决这个问题有什么建议吗?
最佳答案
index.html:
<!DOCTYPE html>
<html>
<head>
<!-- For html5 (default is UTF-8) -->
<meta charaset="UTF-8">
<title>Phantom JS Example</title>
<style>
img#red {
position: absolute;
left: 100px;
top: 100px;
z-index: 5; #***z-index set by CSS****
}
img#black {
position: absolute;
left: 100px;
top: 100px;
z-index: 2; #***z-index set by CSS****
}
</style>
</head>
<body>
<div>Hello</div>
<img src="4row_red.png" id="red" width="40" height="40">
<img src="4row_black.png" id="black" width="40" height="40">
<script>
window.onload = function() {
var red = document.getElementById('red');
red.style.zIndex = "0"; #****z-idex set by JAVASCRIPT****
};
</script>
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550) #For bug
driver.get("http://localhost:8000")
png = driver.find_element_by_id('red')
#print png.css_value('zIndex') <--AttributeError: 'WebElement' object has no attribute 'css_value'
print "{} id={}-> {}".format(
png.tag_name,
png.get_attribute('id'),
png.value_of_css_property('zIndex')
)
#print png.style('zIndex') <--AttributeError: 'WebElement' object has no attribute 'style'
print "get_attribute('zIndex') -> {}".format(
png.get_attribute('zIndex')
)
print '-' * 20
imgs = driver.find_elements_by_tag_name('img')
for img in imgs:
print "{} id={}-> {}".format(
img.tag_name,
img.get_attribute('id'),
img.value_of_css_property('zIndex')
)
print "get_attribute('zIndex') -> {}".format(
imgs[-1].get_attribute('zIndex')
)
print '-' * 20
all_tags = driver.find_elements_by_tag_name('*')
for tag in all_tags:
print "{} --> {}".format(
tag.tag_name,
tag.value_of_css_property('zIndex')
)
driver.quit()
--output:--
img id=red-> 1 #Found the z-index set by the js.
get_attribute('zIndex') -> None #Didn't find the z-index set by the js
--------------------
img id=red-> 1
img id=black-> 3 #Found the z-index set by the css stylesheet
get_attribute('zIndex') -> None #Didn't find the z-index set by the css stylesheet
--------------------
html --> 0
head --> auto
meta --> auto
title --> auto
style --> auto
body --> auto
div --> auto
img --> 1
img --> 3
script --> auto
设置:
$ pip install selenium
$ brew install phantomjs
https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/
value_of_css_property(property_name):
返回 CSS 属性的值
get_attribute(名称):
获取元素的给定属性。
如果已设置,此方法将返回给定属性的值,否则返回具有相同名称的属性的值(如果存在),否则返回 None。
被认为是真实的值,即等于“真”或“假”,作为 bool 值返回。所有其他非 None 值都作为字符串返回。对于不存在的属性或属性,返回 None。
参数:
name - 要检索的属性/属性的名称。
不是很好的文档。
关于python - 在 Python 中为 CSS 属性值解析呈现的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27804457/