一、查看輸入框ID
點(diǎn)擊開發(fā)人員工具頁面的左上角的按鈕(下圖藍(lán)色標(biāo)志)伯诬,觸碰界面即可在右側(cè)格式代碼中顯示對于的ID晚唇,class等信息。用于元素定位盗似。
輸入框的ID顯示‘kw’,所以定位輸入框的代碼:
web.find_element_by_id('kw')
二哩陕、向輸入框中輸入需要搜索的信息
sr.send_keys('翻譯')
三、獲取按鈕的定位元素赫舒,點(diǎn)擊搜索
button = web.find_element_by_class_name('s_btn')
button.click()
四悍及、查看 獲取元素的class屬性
print(sr.get_attribute('class'))
代碼:
from seleniumimport webdriver
from selenium.webdriver.chrome.optionsimport Options
from selenium.webdriver.common.byimport By
from selenium.webdriver.common.keysimport Keys
import time
options_cha = Options()
options_cha.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
chrome_driver ="/usr/local/bin/chromedriver"
web = webdriver.Chrome(chrome_driver, options=options_cha)
print(web.title)
web.get("https://www.baidu.com/")# 打開百度瀏覽器
sr = web.find_element_by_id('kw')
print(sr.get_attribute('class'))
sr.send_keys('Python')
sr.send_keys(Keys.ENTER)
time.sleep(3)
sr.clear()
sr.send_keys('翻譯')
button = web.find_element_by_class_name('s_btn')
time.sleep(3)
button.click()