I'm trying to locate a 'div' element which has the title 'Type a message'.
The following piece of code works:
div_nodes = driver.find_elements_by_tag_name('div')
for element in div_nodes:
if element.get_attribute('title') == 'Type a message':
element.send_keys(Keys.ENTER)
But this does not work:
element = driver.find_element_by_xpath('//div[@title="Type a message"]')
element.send_keys(Keys.ENTER)
I get the error selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@title="Type a message"]"}
Edit: Here is the relevant part of the code and webpage. I'm passing a phone number and a message to web.whatsapp.com. Below is the working code. If I replace the last 4 lines with find_element_by_xpath, it does not work:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import urllib.parse
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=r'<mypath>/chromedriver.exe', options=options)
qry = {}
qry['phone'] = str(contact_number)
qry['text'] = message
url = "https://web.whatsapp.com/send/?{}".format(urllib.parse.urlencode(qry))
driver.get(url)
div_nodes = driver.find_elements_by_tag_name('div')
for element in div_nodes:
if element.get_attribute('title') == 'Type a message':
element.send_keys(Keys.ENTER)
CodePudding user response:
I tried with this xpath and it works
element = driver.find_element_by_xpath('//div[contains(@title, "message")]')
Alternatively, you can try to click the send button with this
driver.find_element_by_css_selector('span[data-testid="send"]').click()
which also works for me. Let me know if they work for you too.
p.s. I suggest to update the code by using the new functions, because the ones you are using are deprecated.
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
driver = webdriver.Chrome(service=Service(r'<mypath>/chromedriver.exe'), options=options)
div_nodes = driver.find_elements(By.TAG_NAME, 'div')
element = driver.find_element(By.XPATH, '//div[@title="Type a message"]')