Selenium Web控件定位
方法 |
描述 |
方式 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
def id_method():
driver = webdriver.Edge()
url = 'https://www.cnblogs.com/'
driver.get(url)
time.sleep(3)
driver.find_element(By.ID,'sidenav_pick').click()
time.sleep(3)
if __name__ == '__main__':
id_method()
NAME定位
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
def name_method():
driver = webdriver.Edge()
url = 'https://www.baidu.com/'
driver.get(url)
time.sleep(3)
driver.find_element(By.NAME,'tj_briicon').click()
time.sleep(3)
if __name__ == '__main__':
name_method()
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
def css_method():
driver = webdriver.Edge()
url = 'https://www.cnblogs.com/'
driver.get(url)
time.sleep(3)
# 查找类名为bannerbar的div元素
driver.find_element(By.CSS_SELECTOR,'div.bannerbar').click()
# 查找类名为navbar-anonymous的元素
driver.find_element(By.CSS_SELECTOR, '.navbar-anonymous').click()
# 查找id为sidenav_category的元素
driver.find_element(By.CSS_SELECTOR, '#sidenav_category').click()
# 查找第一个标签img的元素
driver.find_element(By.CSS_SELECTOR, 'img').click()
# 查找data-post-id="18095472"的元素
driver.find_element(By.CSS_SELECTOR, '[data-post-id="18095472"]').click()
time.sleep(3)
if __name__ == '__main__':
css_method()
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
def xpath_method():
driver = webdriver.Edge()
url = 'https://www.cnblogs.com/'
driver.get(url)
time.sleep(3)
# 1.定位id为sidenav_candidate的元素
driver.find_element(By.XPATH,"//*[@id='sidenav_candidate']").click()
# 2.定位class为navbar-anonymous的元素
driver.find_element(By.XPATH, "//*[@class='navbar-anonymous']").click()
# 3.定位第一个标签为img的元素
driver.find_element(By.XPATH, "//img").click()
# 4.定位text内容为的元素
driver.find_element(By.XPATH, "//*[text()='候选']").click()
# 5.定位data-post-id为18095472的元素
driver.find_element(By.XPATH, "//*[@data-post-id='18095472']").click()
# 6.定位class为sidenav当中第一个li
driver.find_element(By.XPATH, "//*[@class='sidenav']/li[1]").click()
# 7.定位class以navbar-anony为开头的元素
driver.find_element(By.XPATH, "//*[starts-with(@class,'navbar-anony')]").click()
# 8.定位class为post-item-title且text为Oracle与MySQL的差异和对比的元素
driver.find_element(By.XPATH, "//*[@class='post-item-title' and text()='Oracle与MySQL的差异和对比']").click()
time.sleep(3)
if __name__ == '__main__':
xpath_method()
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
def link_method():
driver = webdriver.Edge()
url = 'https://www.cnblogs.com/'
driver.get(url)
time.sleep(3)
driver.find_element(By.LINK_TEXT,"Oracle与MySQL的差异和对比").click()
time.sleep(3)
if __name__ == '__main__':
link_method()