[英]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.我正在制作一个 Selenium web 刮板,它要求输入用户名并在 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()
Okay so I tried to get the followers from a specific account by myself.好的,所以我尝试自己从特定帐户中获取关注者。 The following code works for me and prints out the number of followers from the specified account:
以下代码适用于我并打印出指定帐户的关注者数量:
from selenium import webdriver
from time import sleep
tiktok_user = input("Enter a TikTok user\n")
driver = webdriver.Safari()
driver.get("https://tiktok.com/@" + tiktok_user)
sleep(2)
followers = driver.find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div/header/h2[1]/div[2]/strong").text
print(followers)
It seems like you inserted a wrong x_path into your scraper.您似乎在刮板中插入了错误的 x_path。 Hope that this helps
希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.