Upload Image on WordPress Website Using Python Selenium

If you’re familiar with Selenium, you may know that image can be uploaded with Selenium. Usually in general input tag is used to upload image. 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 case of WordPress backed website, there is no input tag with upload button in the HTML Source. Because input tag is created dynamically when you select image from browser to upload image manually.

Upload page in wordpress sites

HTML source of 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 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 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!