Python selenium operation pull-down scroll bar method summary

Python selenium operation pull-down scroll bar method summary

In UI automation, you often encounter the problem that the element cannot be identified and cannot be found. There are many reasons, such as not in the iframe, xpath or id is wrong, etc .; but there is one that is not visible on the currently displayed page element, dragging The element comes out after moving the drop bar.

For example, the following web page needs to drag the drop-down bar to find the element of the password input box through selenium.

There are several ways to solve this kind of problem in python. A brief introduction to those who need it:

Method one) Direct operation using js script, the method is as follows:

js="var q=document.getElementById('id').scrollTop=10000"
driver.execute_script(js)

 or:

js="var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)

 

The id here is the id of the scroll bar, but there is no xpath method in js, so this method does not apply to web pages where the scroll bar does not have an id

Method two) Use js script to drag to the designated place

target = driver.find_element_by_id("id_keypair")
driver.execute_script ("arguments [0] .scrollIntoView ();", target) #drag to visible elements

This method can drag the scroll bar to the position of the element that needs to be displayed. This method is more versatile and can be used

Method three) Work around according to the page display, send the tab key

In the page in this example, the password is the input box. During normal manual operation, you can use the tab key to switch to the password box, so according to this idea, you can also send the tab key to switch in python to make the element display

from selenium.webdriver.common.keys import Keys
driver.find_element_by_id("id_login_method_0").send_keys(Keys.TAB)

 

update

When using the robotframe work framework some time ago, there is a very useful function Focus in selenium2library, which will automatically locate the element and study the source code:

    def focus(self, locator):
        """Sets focus to element identified by `locator`."""
        element = self._element_find(locator, True, True)
        self._current_browser().execute_script("arguments[0].focus();", element)

We can see from the source code that this method is consistent with the method 2) we wrote in python ourselves , and the tool encapsulates it for us.

Published 17 original articles · Like1 · Visits 819

Guess you like

Origin blog.csdn.net/weixin_45433031/article/details/105152745