python27+selenium2+chrome实现web元素定位八大方法

环境搭建:

python:python2.7版本;

selenium:selenium2,通过pip install selenium命令进行安装;

chrome:65.0.3325.181

chrome driver:v2.37,把chromedriver.exe文件放到与python.exe相同目录下;

ps:保证chromedriver版本和chrome版本匹配(https://blog.csdn.net/huilan_same/article/details/51896672)

web元素八大定位方法,以百度搜索为例:

#-*- coding:utf-8 -*-

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
url = 'http://www.baidu.com'

driver.get(url)
time.sleep(2)
driver.maximize_window()
time.sleep(2)
driver.refresh()
time.sleep(2)

#通过id定位元素,执行pass
location_id = driver.find_element_by_id('kw')
location_id.clear()
location_id.send_keys('python')
#location_id.send_keys(Keys.RETURN)
location_id.send_keys(Keys.ENTER)

#通过name定位元素,执行fail
location_name = driver.find_elements_by_name('wd')
location_name.send_keys('seleniumm')
location_name.send_keys(Keys.RETURN)

#通过classname定位元素,执行pass
location_classname = driver.find_element_by_class_name('s_ipt')
location_classname.send_keys('java')
location_classname.send_keys(Keys.RETURN)

#通过tagname定位元素,执行pass
location_tagname = driver.find_element_by_tag_name('input')
location_tagname.send_keys('c++')
location_tagname.send_keys(Keys.ENTER)

#通过linkText定位元素,执行pass
location_linktext = driver.find_element_by_link_text('糯米').click()

#通过partial_linktext定位元素,执行pass
#location_partiallinktext = driver.find_element_by_partial_link_text('糯').click()

#通过xpath定位元素,执行pass
location_xpath = driver.find_element_by_xpath('//*[@id="kw"]').send_keys(u'python',Keys.RETURN)

#通过css定位元素,执行pass
location_css = driver.find_element_by_css_selector('#kw').send_keys(u'python',Keys.ENTER)

#driver.find_element_by_css_selector('#kw').send_keys(u'python',Keys.ENTER)

你可能感兴趣的:(python之selenium,python,selenium)