爬虫怎么用css对表格进行定位

html-css017

爬虫怎么用css对表格进行定位,第1张

定位元素方法

这里有各种策略用于定位网页中的元素(locate elements),你可以选择最适合的方案,Selenium提供了一下方法来定义一个页面中的元素:

find_element_by_idfind_element_by_namefind_element_by_xpathfind_element_by_link_textfind_element_by_partial_link_textfind_element_by_tag_namefind_element_by_class_namefind_element_by_css_selector 下面是查找多个元素(这些方法将返回一个列表):

find_elements_by_namefind_elements_by_xpathfind_elements_by_link_textfind_elements_by_partial_link_textfind_elements_by_tag_namefind_elements_by_class_namefind_elements_by_css_selector

除了上面给出的公共方法,这里也有两个在页面对象定位器有用的私有方法。这两个私有方法是find_element和find_elements。

常用方法是通过xpath相对路径进行定位,同时CSS也是比较好的方法。举例:

<form id="loginForm"> 

<input name="username" type="text"> 

<input name="password" type="password"> 

<input name="continue" type="submit" value="Login"> 

<input name="continue" type="button" value="Clear">

</form>

定位username元素的方法如下:

username = driver.find_element_by_xpath("//form[input/@name='username']")

username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")

username = driver.find_element_by_xpath("//input[@name='username']")

[1] 第一个form元素通过一个input子元素,name属性和值为username实现

[2] 通过id=loginForm值的form元素找到第一个input子元素

[3] 属性名为name且值为username的第一个input元素

先来看例子吧:

<HTML>

<head>

<style>

.red{border:2px solid red}

</style>

</head>

<body>

<div style="padding:10pxwidth:100px" class="red">

<div id="a" class="red">AAAA</div>

<div id="b" class="red">BBBB</div>

</div>

</body>

</html>

以上代码在浏览器中的显示效果如下:

AAAA

BBBB

下面通过position属性来把AAAA往上移动8px,在head的style里面加入#a{position:relativetop:-8px}即:

<HTML>

<head>

<style>

.red{border:2px solid red}

#a{position:relativetop:-8px}

</style>

</head>

<body>

<div style="padding:10pxwidth:100px" class="red">

<div id="a" class="red">AAAA</div>

<div id="b" class="red">BBBB</div>

</div>

</body>

</html>

效果如下:

AAAA

BBBB

而如果通过margin-top:-8px来调整的话,即:

<HTML>

<head>

<style>

.red{border:2px solid red}

#a{margin-top:-8px}

</style>

</head>

<body>

<div style="padding:10pxwidth:100px" class="red">

<div id="a" class="red">AAAA</div>

<div id="b" class="red">BBBB</div>

</div>

</body>

</html>

效果如下:

AAAA

BBBB

看到不同了吧,用position属性来调整的时候,只是被调整的div移动了,而下面的div不会动;用margin属性调整就不同了,下面的div也会相应的向上移动8px,但是并不影响下面的padding值。