Upload Image on WordPress Website Using Python Selenium

Adnan Alam
May 12, 2018 · 2 min read

If you’re familiar with Selenium, you may know that the image can be uploaded with Selenium. Usually in general input tag is used to upload images. In that case, we find the input tag by Selenium then with that selected input tag send_keys() function is used to upload image.

But in the case of the WordPress backed website, there is no input tag with the upload button in the HTML Source. Because the input tag is created dynamically when you select an image from the browser to upload images manually.

Upload page in wordpress sites

HTML source of the upload button typically looks like this:

<button type="button" class="browser button button-hero" id="__wp-uploader-id-1" style="display: inline-block; position: relative; z-index: 1;">
<font style="vertical-align: inherit;">
<font style="vertical-align: inherit;">Choose files</font>
</font>
</button>

If you look at the page source when you upload an image, the input tag is created dynamically with an id which starts with ‘html5_’. This part of id doesn’t change.

<input id=”html5_7bc1545i41pq2f7f1voce561a0e8" style=”font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;” multiple=”” accept=”” type=”file”/>

So, here the trick we will do:
As we are going to upload an image via Selenium, so we will find the input tag generated dynamically by WordPress with Selenium using Xpath and will use send_keys() to pass the image path. Image path must be absolute and the id will start with ‘html5_’.

image = '/path/to/image.jpg'
input_tag = “//input[starts-with(@id,’html5_’)]”
driver.find_element_by_xpath(input_tag).send_keys(image)

So, this will add an input tag in the HTML of the upload page, then the image will be uploaded with this input tag.

Done!

Dreamcatcher IT’s Blog

Dreamcatcher IT is a hub of eerie minds keen for desired accomplishment; stirred by technology to reinvent possibilities.

Adnan Alam

Written by

Dreamcatcher IT’s Blog

Dreamcatcher IT is a hub of eerie minds keen for desired accomplishment; stirred by technology to reinvent possibilities.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade