元素不可见
如图,想要控制selenium在该输入框内输入路径,但是点击该输入框在该文件管理器非全屏的情况下会触发点击的是个人空间箭头的情况:
也就是并没有找到真正的输入框,但是通过控制台选择元素的方式无法找到真正的输入框,那么很可能是因为输入框被隐藏了,只有在手动点击后才会显示出来。
点击输入框后:
如果Selenium
直接选择该输入框,由于该输入框不可见,无法点击,也无法输入内容,因此,我们需要先通过JavaScript
代码更改该输入框的style
属性,使其可见,然后再点击选中后输入内容即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.keys import Keysimport timefrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport pyperclip driver = webdriver.Chrome() driver.get('https://cloud.shinebook.net' ) link = driver.find_elements(By.CLASS_NAME, 'menu-desktop-app-root' ) my_computer = [x for x in link if '我的电脑' == x.text][0 ] action_chains = ActionChains(driver) action_chains.double_click(my_computer).perform() header_address = driver.find_elements(By.CLASS_NAME, 'header-address-input' )[0 ] driver.execute_script('document.getElementsByClassName(\'header-address-input\')[0].style=\'display: block;\'' ) action_chains.move_to_element(header_address).click().pause(1 ).key_down(Keys.CONTROL).send_keys('a' ).key_up(Keys.CONTROL).send_keys('/var/www/hexo/source/_posts/人工智能/理论基础/深度学习/picture/' ).send_keys(Keys.ENTER).perform()
无法使用鼠标滚轮
由于kodbox
的文件显示用的是懒加载模式,只有当滑动到文件可见时才会加载该文件,因此,需要使用鼠标滚轮或者上下按键来滑动页面。
在其他网站,如果直接使用鼠标滚轮,可以使整个网页上下滑动,但是在kodbox
的文件管理器中,我们需要的是对其中的某个部分进行上下滚动。
尝试使用selenium
的鼠标聚焦在中间有文件的位置,然后使用鼠标滚轮,发现这样依旧没有效果。
没有效果的原因是使用了ActionChains
中的scroll_by_amount()
,其是以当前视窗的左上角为原点,按指定偏移量滚动页面,这样就无法滚动某个局部模块。
解决方法有三个,一个是继续使用ActionChains
,使用局部的滚轮:scroll_from_origin(scroll_origin, delta_x, delta_y)
1 2 3 4 5 6 7 from selenium.webdriver.common.actions.wheel_input import ScrollOrigin files = driver.find_elements(By.CLASS_NAME, 'file-continer' )[0 ] origin = ScrollOrigin.from_element(files) action_chains.scroll_from_origin(origin, 0 , 50 ).perform()
另一种方法是使用JavaScript
代码,选择该元素后下滑
1 driver.execute_script("document.getElementsByClassName('file-continer')[0].scroll(0, 10)" )
还有一种方法是不使用鼠标滚轮,使用鼠标点击其中的某个文件后,使用下箭头来选中下面的文件,自动实现下滑。