首页 > 解决方案 > Selenium can't locate element after I change desktop

问题描述

So I have this part of the code:

 buttons = browser.driver.find_element_by_id('buttons')
 camera_icon = buttons.find_element_by_class_name('style-scope yt-icon-button')
 camera_icon.click() 

I am trying to click the upload button on youtube, it works perfectly fine when I stay on the browser's desktop(fullscreen). If I start the program and leave the webdriver to work in the background, while I navigate to another desktop, it can't locate 'style-scope yt-icon-button' for some reason.

Any help/tips on this is much appreciated!

标签: pythonselenium

解决方案


It might be timing issue. So make sure you are using appropriate wait mechanism in your script. Introduce implicit and explicit wait conditions.

element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".style-scope.yt-icon-button")) 
element.click() 

Import below package for this

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Moreover, It seems the issue with your locator. there are 2 classes style-scope and yt-icon-button. as far as i know class selector find_element_by_class_name doesn't support compound classes.

camera_icon = buttons.find_element_by_class_name('style-scope yt-icon-button')

should be

camera_icon = buttons.find_element_by_css_selector('.style-scope.yt-icon-button')

推荐阅读