Home > front end >  Click on the button with Selenium, using the button text as a search element
Click on the button with Selenium, using the button text as a search element

Time:09-26

I would like to click on the Google "News" button (after searching for something). I would like to search using the text News (in my case "Notizie") as an element. Google sometimes changes the names of the elements, so I would like to use the "News" element because it is always the same

I use this, but it doesn't work:

WebDriverWait (driver, 20) .until (EC.element_to_be_clickable ((By.CSS_SELECTOR, "div [aria-label = 'News']"))). Click ()

How can I do?

enter image description here

enter image description here

CodePudding user response:

sorry for the delay.

after understanding you correctly, you want to search for an element by its text and click on it.

for the record, you use WebDriverWait (driver, 20) .until (EC.element_to_be_clickable while its a great practice you need to understand that if its your first click, then the driver will not click until all elements are visible, and therefore driver.find_element().click() does the same job

also a quick disclaimer, not all google searches show the "news" button in the options bar, and here's a sample code of what you want.

from time import sleep
from seleniumwire import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.google.com/search?q=weather')
newsButton = driver.find_element(By.LINK_TEXT, 'News')
newsButton.click()
sleep(5) 

you look for an element by its text with By.LINK_TEXT

and here's your code it it:

WebDriverWait (driver, 20) .until (EC.element_to_be_clickable ((By.LINK_TEXT, "News"))). Click ()

also check out By.PARTIAL_LINK_TEXT

good luck and sorry again for the misunderstanding, happy coding :)

update

it seems that the By.LINK_NAME filter only finds elements by text that are links, or in a <a> tag, and that's why it wont catch the "Tools" button, but the tools button is static, therefor you can access it with a normal css selector or xpath

  • Related