Last post Brief
stay Last blog post It has been learned in: using execute to send a request to the remote server will interact with the browser through webdriver, and sending the defined command constant can obtain some relevant information.
Where the execute method implementation is already on A blog post There are implementation instructions in. And we already know the webdriver base class( selenium.webdriver.remote Webdriver), the basic method of operating page elements is implemented.
Comprehensive learning through simple application
Suppose we need to open Baidu now, how to search "CSDN A757291228"?
By finding the webdriver base class( selenium.webdriver.remote.webdriver) found the following ways to find elements:
def find_element_by_id(self, id_): """Finds an element by id. :Args: - id\_ - The id of the element to be found. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_id('foo') """ return self.find_element(by=By.ID, value=id_) def find_elements_by_id(self, id_): """ Finds multiple elements by id. :Args: - id\_ - The id of the elements to be found. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: elements = driver.find_elements_by_id('foo') """ return self.find_elements(by=By.ID, value=id_) def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :Args: - xpath - The xpath locator of the element to find. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_xpath('//div/td[1]') """ return self.find_element(by=By.XPATH, value=xpath) def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :Args: - xpath - The xpath locator of the elements to be found. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]") """ return self.find_elements(by=By.XPATH, value=xpath) def find_element_by_link_text(self, link_text): """ Finds an element by link text. :Args: - link_text: The text of the element to be found. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_link_text('Sign In') """ return self.find_element(by=By.LINK_TEXT, value=link_text) def find_elements_by_link_text(self, text): """ Finds elements by link text. :Args: - link_text: The text of the elements to be found. :Returns: - list of webelement - a list with elements if any was found. an empty list if not :Usage: elements = driver.find_elements_by_link_text('Sign In') """ return self.find_elements(by=By.LINK_TEXT, value=text) def find_element_by_partial_link_text(self, link_text): """ Finds an element by a partial match of its link text. :Args: - link_text: The text of the element to partially match on. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_partial_link_text('Sign') """ return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) def find_elements_by_partial_link_text(self, link_text): """ Finds elements by a partial match of their link text. :Args: - link_text: The text of the element to partial match on. :Returns: - list of webelement - a list with elements if any was found. an empty list if not :Usage: elements = driver.find_elements_by_partial_link_text('Sign') """ return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text) def find_element_by_name(self, name): """ Finds an element by name. :Args: - name: The name of the element to find. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_name('foo') """ return self.find_element(by=By.NAME, value=name) def find_elements_by_name(self, name): """ Finds elements by name. :Args: - name: The name of the elements to find. :Returns: - list of webelement - a list with elements if any was found. an empty list if not :Usage: elements = driver.find_elements_by_name('foo') """ return self.find_elements(by=By.NAME, value=name) def find_element_by_tag_name(self, name): """ Finds an element by tag name. :Args: - name - name of html tag (eg: h1, a, span) :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_tag_name('h1') """ return self.find_element(by=By.TAG_NAME, value=name) def find_elements_by_tag_name(self, name): """ Finds elements by tag name. :Args: - name - name of html tag (eg: h1, a, span) :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: elements = driver.find_elements_by_tag_name('h1') """ return self.find_elements(by=By.TAG_NAME, value=name) def find_element_by_class_name(self, name): """ Finds an element by class name. :Args: - name: The class name of the element to find. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_class_name('foo') """ return self.find_element(by=By.CLASS_NAME, value=name) def find_elements_by_class_name(self, name): """ Finds elements by class name. :Args: - name: The class name of the elements to find. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: elements = driver.find_elements_by_class_name('foo') """ return self.find_elements(by=By.CLASS_NAME, value=name) def find_element_by_css_selector(self, css_selector): """ Finds an element by css selector. :Args: - css_selector - CSS selector string, ex: 'a.nav#home' :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_css_selector('#foo') """ return self.find_element(by=By.CSS_SELECTOR, value=css_selector) def find_elements_by_css_selector(self, css_selector): """ Finds elements by css selector. :Args: - css_selector - CSS selector string, ex: 'a.nav#home' :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: elements = driver.find_elements_by_css_selector('.foo') """ return self.find_elements(by=By.CSS_SELECTOR, value=css_selector) def find_element(self, by=By.ID, value=None): """ Find an element given a By strategy and locator. Prefer the find_element_by_* methods when possible. :Usage: element = driver.find_element(By.ID, 'foo') :rtype: WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value'] def find_elements(self, by=By.ID, value=None): """ Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when possible. :Usage: elements = driver.find_elements(By.CLASS_NAME, 'foo') :rtype: list of WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value # Return empty list if driver returns null # See https://github.com/SeleniumHQ/selenium/issues/4555 return self.execute(Command.FIND_ELEMENTS, { 'using': by, 'value': value})['value'] or []
From the above implementation methods, the implementation of the execute method is not described here. It has been explained in the previous section, and this section mainly introduces the use of the method.
First look at find_ element_ By_ The use of ID method has been described in the method description:
element = driver.find_element_by_id('foo')
The annotation of the method is as follows (for clarity, use screenshots to show the annotation):
Note that find_ element_ By_ The id method finds the element whose id is the specified value and returns the element.
The specific implementation is as follows:
self.find_element(by=By.ID, value=id_)
The above implementation calls find_element method, and the value passed in by is By.ID , and then pass in the specific value; first look at the by class( selenium.webdriver.common.by):
class By(object): """ Set of supported locator strategies. """ ID = "id" XPATH = "xpath" LINK_TEXT = "link text" PARTIAL_LINK_TEXT = "partial link text" NAME = "name" TAG_NAME = "tag name" CLASS_NAME = "class name" CSS_SELECTOR = "css selector"
This class and command( selenium.webdriver.remote The. Command) class has a similar function. The previous section has shown that command does not describe By here.
See find here_ Element method implementation:
def find_element(self, =By.ID, value=None): """ Find an element given a By strategy and locator. Prefer the find_element_by_* methods when possible. :Usage: element = driver.find_element(By.ID, 'foo') :rtype: WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SEhj0ECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value']
The above class first determines the search type, and then splices the values. Finally, it passes the search method and value into the execute method, and then returns the element object.
Almost all the element search methods are the same. We can simply use this function.
Before writing the code, we need to open the baidu website and check the element to find the id value:
If the id value of the input box is kw, the code should be as follows:
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.baidu.com/") input = driver.find_element_by_id('kw') # print('author blog: https://blog.csdn.net/A757291228 ) #Support original, reprint please post link
Because the returned element is the element object after the element is found:
In element class( selenium.webdriver.remote.webelement), find the following methods:
def send_keys(self, *value): """Simulates typing into the element. :Args: - value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) """ # transfer file to another machine only if remote driver is used # the same behaviour as for java binding if self.parent._is_remote: local_file = self.parent.file_detector.is_local_file(*value) if local_file is not None: value = self._upload(local_file) self._execute(Command.SEND_KEYS_TO_ELEMENT, {'text': "".join(keys_to_typing(value)), 'value': keys_to_typing(value)}) # Private Methods def _execute(self, command, params=None): """Executes a command against the underlying HTML element. Args: command: The name of the command to _execute as a string. params: A dictionary of named parameters to send with the command. Returns: The command's JSON response loaded into a dictionary object. """ if not params: params = {} params['id'] = self._id return self._parent.execute(command, params)
Know send_keys also get results by sending commands through execute. Got send in the comment_ Keys are used as follows:
form_textfield.send_keys("admin")
We modified the previous code:
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.baidu.com/") input = driver.find_element_by_id('kw') input.send_keys("CSDN A757291228") # print('author blog: https://blog.csdn.net/A757291228 ) #Support original, reprint please post link
At last, we can check and click to complete the automatic search function; we continue to check the element class and find the following methods:
def click(self): """Clicks the element.""" self._execute(Command.CLICK_ELEMENT)
Click method and send_ The keys method has the same implementation, which is not covered in detail. Click directly to click the element. Find the id of Baidu search click button:
The modification code is as follows:
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.baidu.com/") input = driver.find_element_by_id('kw') input.send_keys("CSDN A757291228") enter = driver.find_element_by_id('su') enter.click() # print('author blog: https://blog.csdn.net/A757291228 ) #Support original, reprint please post link
The operation results are as follows:
summary
We simply learned to use selenium to open the browser and search for "CSDN A757191228". In this simple example, we learned not only the original lines of the code in this example, but also the location of other function functions through implementation analysis. We can realize the function we want through these function functions!
From the framework implementation, we can learn the use of the framework with half the effort and understand the implementation principle of the framework, which is more conducive to our development and use.