Issue
I am creating a Python script (using selenium) that posts texts
and media(images)
automatically.
The script works successfully when posting texts
, but not when try to post an image. The error simply says
" Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div"...
I use the following code to click the Twitter Media button in terms of opening my Windows explorer to prepare for getting into my image folder (see also the highlighted Media button in the image).
driver.find_element(by.XPATH, image_xpath).click()
time.sleep(2)
driver.find_element(by.XPATH, image_xpath).send_keys(image)
Solution
There is an input tag available in twitter for uploading file. You can use that locator for uploading file.
Below code is able to tweet an image:
Environment:
Python 3.9.5
OS: Windows
URL = "https://twitter.com/login"
driver.get(URL)
driver.maximize_window()
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.NAME, "text"))).send_keys("your username")
driver.find_element(By.XPATH, '(//*[@role="button"]//following::span[contains(.,"Next")])[2]').click()
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.NAME, "password"))).send_keys("your passowrd")
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//div[@data-testid='LoginForm_Login_Button']"))).click()
sleep(5)
imagePath = driver.find_element(By.XPATH, "//*[@data-testid='fileInput']")
imagePath.send_keys("C:\\Users\\username\\Documents\\Personal\\selenium.png")
tweetButton = driver.find_element(By.XPATH, "//*[@data-testid='tweetButtonInline']")
tweetButton.click()
Output:
Input File Tag:
Answered By - QualityMatters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.