I needed to upload a lot of images (10,000 or more) to wordpress, and I tried to use "Media UP FTP", but I got an error probably because there were too many. In the first place, it took too long to load and I couldn't upload properly. Therefore, I decided to operate the browser with python and upload the image to Wordpress like RPA. Affinger5 is used for the Wordpress theme. I haven't used any other theme, so I don't know if it works in other environments. The browser used is Chrome.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.keys import Keys
import glob
import os
#Function to temporarily stop browser operation
def sleep(sleep_time):
time.sleep(sleep_time)
#Log in to Wordpress.
driver = webdriver.Chrome()
wordpress_url = "URL of my Wordpress"
driver.get(wordpress_url)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "wp-submit")))
# ID/Enter PASS
sleep(0.1)
ID = driver.find_element_by_id("user_login")
ID.send_keys("ID to log in")
sleep(0.1)
password = driver.find_element_by_id("user_pass")
password.send_keys("Password to log in")
sleep(0.1)
#Click the login button
login_button = driver.find_element_by_name("wp-submit")
login_button.click()
sleep(0.1)
#Move to the posting screen
driver.get("URL of the posting screen")
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "footer-upgrade")))
sleep(0.1)
#Go to media upload
driver.get("URL")
#Specify the folder where the images are saved
#Specify only JPG this time
imgs = glob.glob(r"C:\img\*.jpg ")
#Code to upload image
#Before uploading an image, you have to upload the image yourself by the same procedure
#Since you operate Explorer directly, when you press the "Select File" button, the folder you want to upload must be open.
for img in imgs:
media = driver.find_element_by_id("plupload-browse-button")
sleep(0.1)
media.click()
sleep(0.3)
#The name of the image is the same as the original image
img_name = os.path.basename(img)
#Copy and paste of image name
pyperclip.copy(img_name)
pgui.hotkey('ctrl', 'v')
sleep(0.3)
#Press ENTER to select an image and close Explorer.
pgui.typewrite(['enter'])
sleep(0.1)
You will not be able to use your computer while the code is running, because you are just letting your computer do your work. Also, you will need the Chrome Driver to use the webdriver, so please download the one that corresponds to the version of Chrome you are using. Perhaps you also need to set environment variables. I think other people have explained it in detail, so please look for it.
Recommended Posts