Could not find/use the right xpath of the Twitter Media button, why?

Question:

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)

The Twitter Media Button

Asked By: Sarah Zida

||

Answers:

to upload an image, if you have an input tag with attribute type as file

you can directly use the send_keys to upload an image.

time.sleep(2)
driver.find_element(by.XPATH, image_xpath).send_keys("full file path of image")

I would recommend inducing ExplicitWait

wait = WebDriverWait(driver, 30)
wait.until(EC.visibility_of_element_located((By.XPATH, "image_xpath"))).send_keys("full file path of image")

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Note that you should not click on a button to open a windows pop. Once you are on upload image, directly send the keys.

Answered By: cruisepandey

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:

enter image description here

Input File Tag:

enter image description here

Answered By: QualityMatters

Did someone also has the xpath for the Share button on Twitter?

username_field = driver.find_element(By.XPATH, '//div[@class="css-1dbjc4n r-xoduu5"]//*[name()="svg"]')
username_field.click()

Thanks

Answered By: Mr Mihai Costache