selenium 介绍

使用selenium中webdriver模块对浏览器进行操作

from selenium import webdriver   ###导入模块

b = webdriver.Ie()                         ###打开ie浏览器

b.get('http://www.baidu.com')      ###打开一个网页

b.title,current_url                        ###使用title、url判断打开的网页是否正确

ele = b.find_element_by_id('根据id定位元素')

ele = b.find_element_by_name('根据name定位元素')

ele.send_keys('想要输入的内容')

ele.clear()    ###清除输入的内容

b.back()      ###退回上一步

###元素定位

ele1 = b.find_element_by_link_text('百度一下')  ###根据定位页面文字内容来点击按钮

ele1 = b.find_element_by_partial_link_text('百度一')  ###模糊定位页面文字内容来点击按钮

如果页面有很多相似的内容,元素又没有id或name等,可以用css定位,可以用Firebug查看元素,然后复制css路径给值

ele_css = b.find_element_by_css_selector('粘贴上一步复制的值')

如果没有找到可以使用css特有语法查找

ele = b.find_element_by_css_selector('input[id=\'search\']')    ###如果单引号内使用单引号,必须使用转意符

ele = b.find_element_by_css_selector('img[alt="对应的文字"]')

 

xpath定位

xml路径语言:用来确定xml文档中某部分位置语言,用于在xml文档中通过元素和属性进行导航

ele =  b.find_element_by_xpath('html/body/from/input')  ###查找第一个input

ele =  b.find_element_by_xpath('html/body/from/input[2]')  ###查找同级下的第二个input

ele.get_attribute('name')   ###获取属性

ele =  b.find_element_by_xpath('//from//input..')

ele =  b.find_element_by_xpath('//input[@id]')  ###第一个  选取所有xxx元素有id属性的元素 

ele =  b.find_element_by_xpath('//input[not(@id)]')   ####其他的

ele =  b.find_element_by_xpath('//input[@name="firstname"]')   ##选取所有xxx元素id属性为yyy的元素 

 

元素的操作方式

 

posted @ 2018-08-23 22:13  黄瓜不是好瓜  阅读(120)  评论(0编辑  收藏  举报