Selenium positioning element class spaces - Composite class node

In HTML, the node has three common attributes, namely, id, name and class, where a class is a special property that supports a plurality of class names, separated by a space, as shown below:

class contains elements of space

Have you noticed how selenium in find_element_by_class_name, is by_class_name instead, by_class it?
First, we must distinguish the difference between class and attributes of class_name, class attribute node can contain multiple class_name, each separated by a space, as shown above, this button is actually a link, class attribute value "btn btn-primary my-2 ", which comprises three class_name, respectively "btn", "btn-primary ", "my-2", by the developer Ctrl + F search tool press, we can find "btn-primary" this class_name is unique. we can use it to locate.

There are three kinds of targeting:

  • Class_name by a unique positioning: dr.find_element_by_class_name('btn-primary')
  • By using the full class attribute xpath Location: dr.find_element_by_xpath ( '// a [@ class = "btn btn-primary my-2"]')
  • Use css selector, by a property or property portfolio positioning ( recommended ):
    dr.find_element_by_css_selector('.btn-primary')ordr.find_element_by_css_selector('.btn-primary.my-2')

Sample code is as follows:

from selenium import webdriver

dr = webdriver.Chrome()
dr.get('http://qaschool.cn/')

# dr.find_element_by_class_name('btn-primary').click()  # 通过某个class_name定位
# dr.find_element_by_xpath('//a[@class="btn btn-primary my-2"]').click()  # 通过xpath结合完整的class属性定位

# dr.find_element_by_css_selector('.btn-primary').click()  # 通过css selector结合某个class_name定位
dr.find_element_by_css_selector('.btn-primary.my-2').click()  # 通过css selector结合多个class_name定位

Guess you like

Origin www.cnblogs.com/superhin/p/11454865.html