from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep driver = webdriver.Chrome() driver.get('http://www.baidu.com') # 隐式等待5秒 driver.implicitly_wait(5) loc = (By.XPATH, '//input[@id="kw"]') driver.find_element(*loc).send_keys('selenium') driver.find_element(By.XPATH, '//input[@id="su"]').click() wait = WebDriverWait(driver, 20) loc = (By.XPATH, '//b[text()="selenium"]/parent::span') wait.until(EC.visibility_of_element_located(loc)) driver.find_element(*loc).click() sleep(3) driver.quit()写下注释
时间: 2023-12-06 09:43:45 浏览: 408
这段代码使用了Selenium库来控制Chrome浏览器自动化测试。具体注释如下:
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
# 初始化一个Chrome浏览器实例
driver = webdriver.Chrome()
# 打开百度首页
driver.get('http://www.baidu.com')
# 隐式等待5秒
driver.implicitly_wait(5)
# 定位搜索框并输入关键词'selenium'
loc = (By.XPATH, '//input[@id="kw"]')
driver.find_element(*loc).send_keys('selenium')
# 定位搜索按钮并点击
loc = (By.XPATH, '//input[@id="su"]')
driver.find_element(*loc).click()
# 显式等待20秒,直到页面上的'selenium'元素可见
wait = WebDriverWait(driver, 20)
loc = (By.XPATH, '//b[text()="selenium"]/parent::span')
wait.until(EC.visibility_of_element_located(loc))
# 点击'selenium'元素
driver.find_element(*loc).click()
# 停留3秒后关闭浏览器
sleep(3)
driver.quit()
```
这段代码的功能是:打开百度首页,输入关键词"selenium"进行搜索,然后在搜索结果页面中点击"百度百科"中的"selenium"词条,最后停留3秒后关闭浏览器。其中使用了隐式等待和显式等待来控制程序等待页面加载完成。
阅读全文