Selenium2+python automation 33-file upload (send_keys)

foreword

File upload is a very common function on web pages, but it is not so simple to operate successfully in automation.

Generally divided into two scenarios: one is the input tag, which can be easily solved with the send_keys() method provided by selenium;

Another non-input tag is more difficult to implement, you can use the autoit tool or the SendKeys third-party library.

This article takes the uploaded image of the blog garden as an example, and solves the problem of file uploading through the send_keys() method

1. Identify the upload button

1. Click the image upload button in the blog garden editor, and the "Upload local image" box will pop up.

2. Use firebug to view the button properties. This upload image button has a very obvious logo. It is an input tag, and the value of the type attribute is file.

As long as these two identifiers are found, we can upload the file directly with the send_keys() method.

2. Positioning iframe

1. It is a bit complicated to locate the image upload button here. First of all, it is on an iframe (if you don’t understand iframe, see this: Selenium2+python automation 14-iframe )

2. The id of this iframe is dynamic, and there is no name attribute, and other attributes are not very obvious

3. Through the search, it is found that there are two iframes on this page, and the iframe that needs to be positioned is in the second position

4. You can locate all iframe tags by tags, and then take the corresponding number.

3. File upload

1. First locate the file upload button and directly call the send_keys() method to achieve it

# coding:utf-8
from selenium import webdriver
import time
profileDir = r'C:\Users\Gloria\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default'
profile = webdriver.FirefoxProfile(profileDir)
driver = webdriver.Firefox (profile)
driver.implicitly_wait(30)
driver.get("http://www.cnblogs.com/yoyoketang/")
driver.find_element_by_link_text("New Essay").click()
time.sleep(3)
# Click on Editor image
driver.find_element_by_css_selector("img.mceIcon").click()
time.sleep(3)
# Locate all iframes, take the second
iframe = driver.find_elements_by_tag_name('iframe')[1]
# Switch to iframe
driver.switch_to_frame(iframe)

# file path
driver.find_element_by_name('file').send_keys(r"D:\test\xuexi\test\14.png")

 

This method does not apply to file uploads with non-input tags, and requires the help of the autoit tool or the SendKeys third-party library.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325454322&siteId=291194637