selenium元素定位方法
元素定位一共有八种方法:
1. id定位
find_element_by_id()
页面元素里有一个且唯一的id="login",如下面:
![](http://upload-images.jianshu.io/upload_images/18773303-cff0c447e373ce9f.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
可以定位到【登录】按钮的方法有
①、driver.find_element_by_id(‘login’)
②、driver.find_element_by_css_selector(‘#login’)
③、driver.find_element_byxpath("//*[@id='login']")
2. name定位
find_element_by_name()
如下图:
![](http://upload-images.jianshu.io/upload_images/18773303-a2b38dbb58be67fe.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
driver.find_element_name('button')
3. class_name
class标准属性,不唯一,通常找一类元素
<div class='cheese'><span>Cheddar</span></div>
![](http://upload-images.jianshu.io/upload_images/18773303-50d50aafb1c33c78.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
4. tag_name
tag名如果是唯一的,可以根据tag定位
如果html有如下:
<iframe src='...'></iframe>
ele=driver.find_element_by_tag_name('iframe')
eles=driver.find_elements_by_tag_name('iframe')
如下图,可以通过iframe定位到输入框
![](http://upload-images.jianshu.io/upload_images/18773303-d85ec416ae09b0a8.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
5.通过链接文本选择元素
对于链接,可以通过链接其链接文本的内容
比如百度的新闻链接
![](http://upload-images.jianshu.io/upload_images/18773303-f092a696ab8a4114.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
6.partial_link
甚至通过部分链接文本选择元素
ele=driver.find_element_partial_link_text('123')
![](http://upload-images.jianshu.io/upload_images/18773303-d5f1ec8185756023.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
7.xpath定位
find_element_by_xpath()
通过//div//p可以查找任意div节点下面的p节点,无论p节点是否是直属节点
eles = food.find_elements_by_xpath('//div//p')
![](http://upload-images.jianshu.io/upload_images/18773303-1aa36582bc1a672b.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
8.CSS定位
find_element_by_css_selector(‘div > *’)
![](http://upload-images.jianshu.io/upload_images/18773303-bbe6d655d5b5f5fb.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)