百度输入框元素:
“百度一下按钮”
from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.baidu.com") #输入框ID定位 driver.find_element_by_id("kw").send_keys("python") #"百度一下“按钮 ID定位 driver.find_element_by_id("su").click()
from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.baidu.com") #输入框class name定位 driver.find_element_by_class_name("s_ipt").send_keys("python") #"百度一下“按钮 class 定位 driver.find_element_by_class_name("s_btn").click()
from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.baidu.com") #输入框 xpath属性层级 定位 driver.find_element_by_xpath("//span[contains(@class, 's_ipt_wr')]/input").send_keys("python") #"百度一下“按钮 xpath属性层级 定位 driver.find_element_by_xpath("//span[@class='bg s_btn_wr']/input").click()
定位一组搜索结果的元素。
from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.baidu.com") #输入框 xpath属性层级 定位 driver.find_element_by_xpath("//span[contains(@class, 's_ipt_wr')]/input").send_keys("廖雪峰python") #"百度一下“按钮 xpath属性层级 定位 driver.find_element_by_xpath("//span[@class='bg s_btn_wr']/input").click() time.sleep(2) #定位一组元素 s = driver.find_elements_by_xpath("//div[@tpl='se_com_default']/h3/a") print(len(s)) s[1].click()
from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.baidu.com") #输入框 xpath属性层级 定位 driver.find_element_by_xpath("//span[contains(@class, 's_ipt_wr')]/input").send_keys("廖雪峰python") #"百度一下“按钮 xpath属性层级 定位 driver.find_element_by_xpath("//span[@class='bg s_btn_wr']/input").click() time.sleep(2) #定位一组元素:css语法 s = driver.find_elements_by_css_selector("[tpl='se_com_default']>h3>a") for i in s: print(i.get_attribute("href"))
练习:博客园登录。
from selenium import webdriver import time driver = webdriver.Firefox() bokeyuan = "https://www.cnblogs.com" driver.get(bokeyuan) time.sleep(2) driver.find_element_by_link_text("登录").click() time.sleep(2) driver.find_element_by_id("mat-input-0").send_keys("*****") driver.find_element_by_id("mat-input-1").send_keys("*****") driver.find_element_by_class_name("mat-button-wrapper").click()