上传过程一般要打开一个本地窗口,从窗口选择本地文件添加。selenium webdriver只要定位上传按钮,通过send_keys添加本地文件路径就可以了,绝对路径和相对路径都可以
1、操作文件上传例子:
upload_file.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>upload_file</title>
<script type="text/javascript" async=""
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js ">
</script>
<link
href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstra p-combined.min.css" rel="stylesheet" />
<script type="text/javascript">
</script>
</head>
<body>
<div class="row-fluid">
<div class="span6 well">
<h3>upload_file</h3>
<input type="file" name="file" />
</div>
</div>
</body>
<script
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap. min.js"></script>
</html>
通过浏览器打开,得到下面界面:
操作上传脚本:
#coding = utf-8
from selenium import webdriver
import time,os
driver = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
driver.implicitly_wait(8)
file_path = os.path.abspath('upload_file.html')#脚本与upload_file.html在同一个目录
driver.get(file_path)
time.sleep(5)
driver.find_element_by_name('file').send_keys('F:\\1.log')#定位上传按钮,添加本地文件
time.sleep(3)
print(driver.title) #把页面的title打印出来
driver.quit()
2、下拉框处理
操作下拉框例子:
drop_down.html
<html>
<body>
<select id="ShippingMethod" οnchange="updateShipping(options[selectedIndex]);" name="ShippingMethod">
<option value="12.51">UPS Next Day Air ==> $12.51</option>
<option value="11.61">UPS Next Day Air Saver ==> $11.61</option>
<option value="10.69">UPS 3 Day Select ==> $10.69</option>
<option value="9.03">UPS 2nd Day Air ==> $9.03</option>
<option value="8.34">UPS Ground ==> $8.34</option>
<option value="9.25">USPS Priority Mail Insured ==> $9.25</option>
<option value="7.45">USPS Priority Mail ==> $7.45</option> <option value="3.20" selected="">USPS First Class ==> $3.20</option>
</select>
</body>
</html
通过浏览器打开:
通过脚本选择下拉列表里的$10.69
#-*-coding=utf-8
from selenium import webdriver
import os,time
driver = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
driver.set_window_size(480,800)
time.sleep(3)
file_path = os.path.abspath('drop_down.html')
driver.get(file_path)
time.sleep(2)
#先定位到下拉框
m = driver.find_element_by_id('ShippingMethod')
m.click()
time.sleep(3)
#再点击下拉框下的选项
m.find_element_by_xpath('//option[@value="10.69"]').click()
time.sleep(3)
driver.quit()
3、对话框的处理
有些弹出的对话框,我们可以通过判断是否为当前窗口的方式进行操作
from time import sleep
import os
import selenium.webdriver.support.ui as ui
driver = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
driver.get('https://www.baidu.com')
nowhandle = driver.current_window_handle #获得当前窗口
allhandles = driver.window_handles
for handle in allhandles:
if handle!=nowhandle: #比较当前窗口是不是原先的窗口
driver.switch_to_window(handle) #获得当前窗口的句柄
driver.find_element_by_class_name('xxxx').click() #在当前窗口操作
driver.switch_to_window(nowhandle) #回到原先的窗口
很荣幸你能翻到这篇文章,也可以关注个人微信公众号,有助于提升寄己,卸卸鼓励!!!