吾八哥學Selenium(二):操作輸入框/按鈕的方法,selenium輸入框
一個web頁面一定少不了輸入框或者按鈕這兩種元素,那麼在Python裡如何使用Selenium操作web頁面裡的輸入框和按鈕呢?本文帶你簡單入門。
本文採用了一個例子,就是利用Selenium開啟百度網頁,然後進行搜尋索引鍵“Python”,執行搜尋動作。具體代碼如下:
Python
# Autor: 5bug# WebSite: http://www.XuePython.wang# 學Python網QQ群: 643829693from selenium import webdriverdriver = webdriver.Chrome("C:/Users/5bug/AppData/Local/Google/Chrome/Application/chromedriver.exe")# driver.maximize_window()driver.get('https://www.baidu.com')input = driver.find_element_by_id('kw')input.send_keys('Python')button = driver.find_element_by_xpath('//*[@id="su"]')print(button.get_attribute("value"))button.click()
運行效果:
這個例子裡面主要使用了如下幾個方法:
find_element_by_id:通過元素id來找元素對象,參數為元素id
find_element_by_xpath:通過xpath來找元素對象,參數為元素xpath
send_keys:向輸入框內發送文本,參數為常值內容
get_attribute:擷取某元素的某個屬性,參數為屬性名稱
文本輸入框還有一個方法clear() 用於清空當前文本
本文首發於學Python網:http://www.XuePython.wang