【Python3 爬虫】U31_selenium定位元素

说明:find_element是获取第一个满足条件的元素。find_elements是获取所有满足条件的元素。

1.使用介绍

find_element_by_id:根据id来查找某个元素。等价于:
submitTag = driver.find_element_by_id('su')
submitTag1 = driver.find_element(By.ID,'su')
 
find_element_by_class_name:根据类名查找元素。 等价于:
submitTag = driver.find_element_by_class_name('su')
submitTag1 = driver.find_element(By.CLASS_NAME,'su')
 
find_element_by_name:根据name属性的值来查找元素。等价于:
submitTag = driver.find_element_by_name('email')
submitTag1 = driver.find_element(By.NAME,'email')
 
find_element_by_tag_name:根据标签名来查找元素。等价于:
submitTag = driver.find_element_by_tag_name('div')
submitTag1 = driver.find_element(By.TAG_NAME,'div')
 
find_element_by_xpath:根据xpath语法来获取元素。等价于:
submitTag = driver.find_element_by_xpath('//div')
submitTag1 = driver.find_element(By.XPATH,'//div')
 
find_element_by_css_selector:根据css选择器选择元素。等价于:
submitTag = driver.find_element_by_css_selector('//div')
submitTag1 = driver.find_element(By.CSS_SELECTOR,'//div')

2.实战案例

2.1 根据ID获取,打开百度,在输入框输入【中国】

# Author:Logan
# Date:2020/4/8  10:29
# IDE:PyCharm
from selenium import webdriver
from selenium.webdriver.common.by import By
# chromedriver的绝对路径

driver_path = r'D:\Python\chromedriver.exe'

# 初始化一个driver,并且指定chromedriver的路径

driver = webdriver.Chrome(executable_path=driver_path)

# 请求网页

driver.get("https://www.baidu.com/")

# inputTag = driver.find_element_by_id('kw')
inputTag = driver.find_element(By.ID,'kw')
inputTag.send_keys("中国")
posted @ 2020-04-08 11:33  OLIVER_QIN  阅读(175)  评论(0编辑  收藏  举报