生活随笔
收集整理的這篇文章主要介紹了
轻松自动化---selenium-webdriver(python) (九)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本節重點:
?
文件上傳操作也比較常見功能之一,上傳功能沒有用到新有方法或函數,關鍵是思路。
上傳過程一般要打開一個本地窗口,從窗口選擇本地文件添加。所以,一般會卡在如何操作本地窗口添加上傳文件。
其實,在selenium??webdriver?沒我們想的那么復雜;只要定位上傳按鈕,通send_keys添加本地文件路徑就可以了。絕對路徑和相對路徑都可以,關鍵是上傳的文件存在。下面通地例子演示。
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/bootstrap-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>
upload.py
#coding=utf-8
from selenium import webdriver
import os,timedriver = webdriver.Firefox()#腳本要與upload_file.html同一目錄
file_path = 'file:///' + os.path.abspath('upload_file.html')
driver.get(file_path)#定位上傳按鈕,添加本地文件
driver.find_element_by_name("file").send_keys('D:\\selenium_use_case\upload_file.txt')
time.sleep(2)driver.quit()
?
?
其它有些應用不好找,所以就自己創建頁面,這樣雖然麻煩,但腳本代碼突出重點。
這里找一139郵箱的實例,有帳號的同學可以測試一下~!
(登陸基礎版的139郵箱,網盤模塊上傳文件。)
139upload.py
#coding=utf-8
from selenium import webdriver
import os,timedriver = webdriver.Firefox()driver.get("http://m.mail.10086.cn")
driver.implicitly_wait(30)#登陸
driver.find_element_by_id("ur").send_keys("手機號")
driver.find_element_by_id("pw").send_keys("密碼")
driver.find_element_by_class_name("loading_btn").click()
time.sleep(3)#進入139網盤模塊
driver.find_element_by_xpath("/html/body/div[3]/a[9]/span[2]").click()
time.sleep(3)#上傳文件
driver.find_element_by_id("id_file").send_keys('D:\\selenium_use_case\upload_file.txt')
time.sleep(5)driver.quit()
總結
以上是生活随笔為你收集整理的轻松自动化---selenium-webdriver(python) (九)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。