Take the Baidu text box as an example:
<form id="form" name="f" action="/s" class="fm"> <span class="bg s_ipt_wr quickdelete-wrap"> <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off"></form>
Locate by ID: find_element_by_id ('kw ')
Locate by name: find_element_by_name ('wd ')
Locate by class: find_element_by_class_name ('s _ ipt ')
Locate by TAG: find_element_by_tag_name ('input ')
In practical applications, tags are rarely used to locate an element. tags are generally used to locate a group of elements.
Locate a group of elements based on tags: find_elements_by_tag_name ('input ')
from selenium import webdriverdr = webdriver.Firefox()dr.get("https://www.baidu.com")inputs = dr.find_elements_by_tag_name(‘input‘)for i in inputs: if i.get_attribute(‘id‘) == "kw": i.send_keys(‘selenium‘)
Locate by text link: find_element_by_link_text ("news ")
When using Chinese, you must declare at the beginning #-*-coding = UTF-8-*-or # Coding = UTF-8
Locate based on some text links: find_element_by_partial_link_text ("new ")
Locate by XPath: find_element_by_xpath ('input [@ ID = "kW"] ')
Locate unique elements except ID name class
Find_element_by_xpath ('// input [@ maxlength = "255"]')
Locate by path
Find_element_by_xpath ("// form [@ ID = 'form' and @ class = 'ffm ']/SPAN/input ")
Location Based on absolute path, but it is not recommended if the path may change or the element is deep.
Find_element_by_xpath ("/html/body/Div [2]/Div/form/SPAN/input ")
Position Based on CSS:
Common CSS selector syntax
Selector |
Description |
. Class |
Class Selector |
# ID |
Id Selector |
* |
Select all elements |
Element |
Select an element |
Element1> element2 |
Select All 2 elements whose parent element is 1 |
Element1 + element2 |
Select All 2 elements next to 1 |
[Artivity = value] |
Select all words whose target is equal to a value. |
E. g:
Find_element_by_css_selector ('. s_ipt ')
Find_element_by_css_selector ('# kW ')
Find_element_by_css_selector ('form. FM> span> input # kW ')
Find_element_by_css_selector ('input [maxlength = "255"] ')
How to locate Elements