一、查看输入框ID
点击开发人员工具页面的左上角的按钮(下图蓝色标志),触碰界面即可在右侧格式代码中显示对于的ID,class等信息。用于元素定位。
输入框的ID显示‘kw’,所以定位输入框的代码:
web.find_element_by_id('kw')
二、向输入框中输入需要搜索的信息
sr.send_keys('翻译')
三、获取按钮的定位元素,点击搜索
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()