python
复制代码
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
url = "https://www.baidu.com/"
driver.get(url)
driver.maximize_window ()
# 输入框:<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
# 百度一下:<input type="submit" id="su" value="百度一下" class="bg s_btn">
# 输入内容:send_keys()
driver.find_element(By.ID, 'kw').send_keys('1111')
sleep(3)
# 点击(鼠标的左击):click()
driver.find_element(By.ID, 'su').click()
sleep(5)
# 清除文本:clear()
driver.find_element(By.ID, 'kw').clear()
sleep(3)
# 提交表单:submit()
driver.find_element(By.ID, 'kw').send_keys('2222')
driver.find_element(By.ID, 'kw').submit()
sleep(10)
# <a href="http://news.baidu.com" target="_blank" class="mnav c-font-normal c-color-t">新闻</a>
# xpath: //*[@id="s-top-left"]/a[1]
# 获取元素的大小:size
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').size) # {'height': 23, 'width': 26}
# 获取元素的文本信息:text
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').text) # 新闻
# 获取元素的内容/属性:get_attribute()
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').get_attribute('innerText')) # 新闻
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').get_attribute('class')) # mnav c-font-normal c-color-t
# 判断元素是否可见:is_display()
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').is_displayed()) # True
# 判断元素是否可用:is_enable()
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').is_enabled()) # True
# 截图:get_screenshot_as_file() 或 save_screenshot()
driver.get_screenshot_as_file('./1png')
driver.save_screenshot('./2.jpg')
sleep(2)
driver.quit()