#code:utf-8
from selenium import webdriver #加载webdriver方法
import time
driver = webdriver.Firefox(executable_path = '/Users/duanlin/Downloads/geckodriver') #创建Firefox对象,调用Firefox浏览器
driver.get("http://www.baidu.com") #在Firefox中输入需要访问的链接
#截图保存
def snapShoot():
pic_time = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) # 获取当前时间
try:
pic_url = driver.get_screenshot_as_file(
"/Users/duanlin/PycharmProjects/seleniumTest/screenshot-pic/" + pic_time + ".png")
print("%s:截图成功!" % pic_url)
except BaseException as msg:
print(msg)
#百度输入框的selector:#kw
#///**页面停留3秒,refresh刷新页面***/
time.sleep(3) #设置页面等待时间
driver.refresh() #刷新页面
snapShoot()
driver.find_element_by_link_text("新闻").click()
driver.refresh() #刷新页面
time.sleep(2)
driver.find_element_by_id("ww").send_keys('头条') #找到百度输入框输入关键字
time.sleep(0.5)
driver.find_element_by_id("s_btn_wr").click()#找到百度页面"百度一下"按钮并点击查询
snapShoot()
driver.find_element_by_partial_link_text('百度首页').click() #当超链接的内容较长时使用模糊匹配
driver.find_element_by_id("kw").send_keys('hello world') #找到百度输入框输入关键字"hello world"
time.sleep(0.5)
driver.find_element_by_id("su").click()#找到百度页面"百度一下"按钮并点击查询
snapShoot()
#百度登陆
# driver.find_element_by_class_name("lb").click() #登录
driver.find_element_by_name("tj_login").click() #登录
driver.find_element_by_id("TANGRAM__PSP_10__footerULoginBtn").click()#点击用户名登陆登录
driver.maximize_window()
time.sleep(2)
snapShoot()
time.sleep(3)
driver.quit()
selenium调用Firefox浏览器时打开失败,必须下载对应版本的geckodriver引入
知识点:
常见获取元素的方法:
find_element_by_id()、find_element_by_partial_link_text()、find_element_by_link_text()、find_element_by_name()、find_element_by_tag_name()
截图方法:get_screenshot_as_file
生成时间撮方法:
time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
优化:自动创建文件夹并保存为时间戳截图
def makeDirctorys():
dir_time = time.strftime("%Y-%m-%d", time.localtime(time.time())) # 获取当前时间的文件夹
print(os.getcwd()) #打印文件目录
try:
File_path = os.getcwd() + '/' + dir_time + '/'
if not os.path.exists(File_path):
os.mkdir(File_path)
print ("目录创建成功:%s" %File_path)
else:
print("目录以存在!!")
except BaseException as msg:
print("创建目录失败:%s" %msg)
return File_path
dirFile_path = makeDirctorys()
#截图保存
def snapShoot():
pic_time = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) # 获取当前时间
try:
pic_url = driver.get_screenshot_as_file(
dirFile_path + pic_time + ".png")
print("%s:截图成功!" % pic_url)
except BaseException as msg:
print(msg)