登录时Selenium无法定位元素



当我尝试使用Selenium点击一个元素时,它只有在我没有登录网站时才有效,否则我得到这个消息:"没有这样的元素:无法定位元素"

如果我从它工作的代码中删除日志序列,问题就在最后的driver.find_element_by_xpath线。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
driver = webdriver.Chrome(ChromeDriverManager().install())

url = "https://rocket-league.com"
driver.get(url)

agreebutton = driver.find_element_by_xpath('//*[@id="acceptPrivacyPolicy"]')
agreebutton.click()
time.sleep(1)
agreebutton2 = driver.find_element_by_xpath('//*[@id="qc-cmp2-ui"]/div[2]/div/button[1]')
agreebutton2.click()
login = driver.find_element_by_xpath('/html/body/header/section[1]/div/div[2]/div/a[1]')
login.click()
email = driver.find_element_by_xpath('/html/body/main/main/section/div/div/div[1]/form/input[2]')
password = driver.find_element_by_xpath('/html/body/main/main/section/div/div/div[1]/form/input[3]')
email.send_keys('xxx')
password.send_keys('xxx')
login2 = driver.find_element_by_xpath('/html/body/main/main/section/div/div/div[1]/form/input[4]')
login2.click()
driver.get("https://rocket-league.com/player/Sun_dance")
time.sleep(1)
decline = driver.find_element_by_xpath('//*[@id="declineNotifications"]')
decline.click()
time.sleep(1)
comments = driver.find_element_by_xpath('/html/body/main/section/div/div/div[3]/div/div[3]/div[1]/div[2]/a[1]')
comments.click()

while True:
pass

解决方法是滚动到元素。

例如:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
found = False
while found == False:
try:
comments = driver.find_element_by_xpath('your xpath')
found = True
except:
ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform()

最新更新