繁体   English   中英

Python-Selenium 没有这样的元素:无法定位元素

[英]Python-Selenium no such element: Unable to locate element

我是编码新手。 我正在尝试制作一个 twitter 机器人,但是当我找到 XPaths 并将其粘贴到我的代码中时,出现错误

我试图找到具有 id、名称、选择器的元素并将其粘贴到我的代码中,但它们都不起作用

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time



class TwitterBot:
    def __init__(self , username , password) :
        self.username = username
        self.password = password


        chrome_options = Options()
        self.bot = webdriver.Chrome(ChromeDriverManager().install() , options = chrome_options)


    def login(self):

        bot = self.bot
        bot.get("https://twitter.com/login")
        time.sleep(5)

        email = bot.find_element(By.XPATH , '/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[5]/label[1]/div[1]/div[2]/div[1]/input[1]')
        email.send_keys(self.username)


        


f = TwitterBot("blabla" ,"blabla")
f.login()

您需要学习如何创建正确、简短且独特的定位符。 非常长的绝对 XPath 和 CSS 选择器极易损坏。
您还需要使用WebDriverWait expected_conditions显式等待,而不是硬编码延迟。
以下代码有效:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_argument('--disable-notifications')

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

url = "https://twitter.com/login"
driver.get(url)

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[autocomplete='username']"))).send_keys("ku-ku")

结果是:
在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM