为啥即使元素存在,硒也会抛出未找到元素的错误? [复制]
Posted
技术标签:
【中文标题】为啥即使元素存在,硒也会抛出未找到元素的错误? [复制]【英文标题】:Why does selenium throw element not found error even when the element is present? [duplicate]为什么即使元素存在,硒也会抛出未找到元素的错误? [复制] 【发布时间】:2021-02-20 11:08:18 【问题描述】:这是我写的,它是一个登录我的 Instagram 帐户的简单程序,凭据已更改:
from selenium import webdriver
import time
import os
class InstaBot:
def __init__(self, username=None, password=None):
self.username = username
self.password = password
self.driver = webdriver.Chrome('./chromedriver.exe')
self.login()
def login(self):
self.driver.get(r'https://www.instagram.com/accounts/login/')
# login_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[3]') # login button xpath changes after text is entered, find first
self.driver.find_element_by_name('username').send_keys(self.username)
self.driver.find_element_by_name('password').send_keys(self.password)
# login_btn.click()
if __name__ == '__main__':
ig_bot = InstaBot(username='temp', password='tempp')
我不知道它为什么会抛出错误。请帮忙。
Traceback (most recent call last):
File "instabot.py", line 30, in <module>
ig_bot = InstaBot(username='temp', password='tempp')
File "instabot.py", line 15, in __init__
self.login()
File "instabot.py", line 23, in login
self.driver.find_element_by_name('username').send_keys(self.username)
File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 496, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value)['value']
File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Program Files\Python37\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":"css selector","selector":"[name="username"]"
(Session info: chrome=86.0.4240.183)
Chrome 确实打开了登录页面,但找不到该元素。
PS:你可能已经猜到我是新手
编辑:
我认为当我使用 time.sleep 几秒钟时,它可以正常工作.... 但我不认为它是修复它的最佳方法,所以请注意它并给我一些建议,或者这就是它的实际工作方式......
【问题讨论】:
【参考方案1】:我找到了答案,是的!!
我应该在搜索元素之前等待页面加载,它们有两种类型:
1 显式等待
2 隐式等待
这些实际上记录在这里:https://selenium-python.readthedocs.io/waits.html
在搜索元素之前应添加以下内容:
WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Sign up")))
为此,顶部需要一些导入行,即
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
编辑1: 我之前用的是隐式的,现在用的是显式的
【讨论】:
以上是关于为啥即使元素存在,硒也会抛出未找到元素的错误? [复制]的主要内容,如果未能解决你的问题,请参考以下文章