selenium自动化测试

对应于webdriver中的定位方法分别是:(现在全部改版成    driver.find_element(By.XPATH,xpath的匹配)

driver.find_element_by_name()——最常用,简单
driver.find_element_by_id()——最常用,简单
driver.find_element_by_class_name()
driver.find_element_by_tag_name()——最不靠谱
driver.find_element_by_link_text()——定位文字连接好用
driver.find_element_by_partial_link_text()——定位文字连接好用
driver.find_element_by_xpath()——最灵活,万能  (我最擅长)
driver.find_element_by_css_selector()
话不多说,上代码:

我自己写的小例子。仅供参考。

下载对应的谷歌驱动,放在自己的的谷歌目录里面。然后写入环境变量。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# 尝试传参
#s = Service("chromedriver.exe")
driver = webdriver.Chrome(service=Service(r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'))

#driver.maximize_window()  # 最大化浏览器
driver.implicitly_wait(23)  # 隐式等待
url = "https://www.baidu.com"
driver.get('https://www.baidu.com')

driver.find_element(By.XPATH,"//input[@id='kw']").send_keys('新版刷新')
driver.find_element(By.XPATH,"//input[@id='su']").click()

print('当前网址是:'+ driver.current_url)





# driver 获取html字符串
# print(driver.page_source)  # 当前网页内容
# with open('1.html', 'w', encoding='gb18030') as f:  # 这里我计入encoding= 'gb18030'是为了解决中文乱码问题
#     f.write(driver.page_source)
# print(driver.current_url)  # 当前网页链接

  

 

posted @ 2019-11-07 13:54  龙卷风之殇  阅读(226)  评论(0)    收藏  举报