dimanche 6 décembre 2020

Selenium error selenium.common.exceptions.NoSuchElementException when trying to access an HTML element via Xpath

I'm making a Selenium web scraper that asks for a username and get the followers of that user in TikTok. Everything was great but suddenly for some reason these errors started appearing

Traceback (most recent call last):
  File "C:\Users\jimos\tiktok_followers\followers.py", line 9, in <module>
    not_found = driver.find_element_by_xpath("//p[@class='jsx-4111167561 title']")
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//p[@class='jsx-4111167561 title']"}
  (Session info: chrome=87.0.4280.88)

Here's my code

from selenium import webdriver
from time import sleep

tiktok_user = input("Enter a TikTok user\n")
PATH = "chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://tiktok.com/@" + tiktok_user)
sleep(2)
not_found = driver.find_element_by_xpath("//p[@class='jsx-4111167561 title']")
followers = driver.find_element_by_xpath("//strong[@title='Followers']")
if not not_found:
    sleep(0.5)
    print("Followers of", tiktok_user + ":", followers.get_attribute('innerHTML'))
    driver.close()
if not_found: 
    if not_found.get_attribute('innerHTML') == "Couldn't find this account":
        print("User not found!")
        driver.close()

Aucun commentaire:

Enregistrer un commentaire