使用selenium写一个程序用于百度搜索按钮的元素定位,使用八种元素定位方法
时间: 2024-06-09 22:08:34 浏览: 3
好的,以下是使用 Selenium 和 Python 3 编写的程序,用于在百度搜索页面中定位搜索按钮元素:
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
# 创建 Chrome 浏览器对象
driver = webdriver.Chrome()
# 打开百度首页
driver.get("https://www.baidu.com/")
# 定位搜索框元素
search_box = driver.find_element(By.ID, "kw")
# 输入搜索关键字
search_box.send_keys("Selenium")
# 定位搜索按钮元素
search_button = None
try:
# 使用 ID 定位
search_button = driver.find_element(By.ID, "su")
except:
pass
if not search_button:
try:
# 使用 Name 定位
search_button = driver.find_element(By.NAME, "wd")
except:
pass
if not search_button:
try:
# 使用 Class Name 定位
search_button = driver.find_element(By.CLASS_NAME, "s_btn")
except:
pass
if not search_button:
try:
# 使用 Tag Name 定位
search_button = driver.find_element(By.TAG_NAME, "input")
except:
pass
if not search_button:
try:
# 使用 Link Text 定位
search_button = driver.find_element(By.LINK_TEXT, "百度一下")
except:
pass
if not search_button:
try:
# 使用 Partial Link Text 定位
search_button = driver.find_element(By.PARTIAL_LINK_TEXT, "一下")
except:
pass
if not search_button:
try:
# 使用 CSS Selector 定位
search_button = driver.find_element(By.CSS_SELECTOR, "#su")
except:
pass
if not search_button:
try:
# 使用 XPath 定位
search_button = driver.find_element(By.XPATH, "//input[@id='su']")
except:
pass
# 点击搜索按钮
search_button.click()
# 关闭浏览器
driver.quit()
```
程序中使用了 8 种元素定位方法,按照优先级从高到低排列分别是:
1. ID 定位
2. Name 定位
3. Class Name 定位
4. Tag Name 定位
5. Link Text 定位
6. Partial Link Text 定位
7. CSS Selector 定位
8. XPath 定位
注意,这些定位方法并不是一定按照这个顺序执行的,程序会逐一尝试各种定位方法,直到找到符合条件的元素为止。同时,定位方法的优先级也可以根据实际情况进行调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)