I am trying to automate the process of liking pages on Facebook. I've got a list of each page's link and I want to open and like them one by one. I think the Like button doesn't have any id or name, but it is in a span class.
<span class="x1lliihq x6ikm8r x10wlt62 x1n2onr6 xlyipyv xuxw1ft">Like</span>
I used this code to find and click on the "Like" button.
def likePages(links, driver):
for link in links:
driver.get(link)
time.sleep(3)
driver.find_element(By.LINK_TEXT, 'Like').click()
And I get the following error when I run the function:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element
The classname attribute values like x1lliihq
, x6ikm8r
, etc, are dynamically generated and is bound to chage sooner/later. They may change next time you access the application afresh or even while next application startup. So can't be used in locators.
Moreover the the element is a <span>
tag so you can't use By.LINK_TEXT
To click on the element Like you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
Using XPATH and text()
:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Like']"))).click()
Using XPATH and contains()
:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(., 'Like')]"))).click()
Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a couple of relevant detailed discussions on NoSuchElementException in: