Python combat: the use of selenium framework to achieve Baidu query

I. Introduction

Recently are learning to use Ali cloud RPA content found using python development, but at the moment Ali cloud RPA is closed source. But the personal feeling and automation development essentially the same. So I read the relevant information online, and made a small case Baidu query, write a blog post now to share knowledge about the use of selenium automation framework.

Second, the installation

1. Install selenium

The first to use pip install selenium

pip install selenium

2. Install ChromeDriver

Installation ChromeDriver, the tool for selenium use Chrome. Mirroring a national address below, download much faster than it is abroad.

http://npm.taobao.org/mirrors/chromedriver/

Download will find and unusual version, download that version need to see your version of Chrome. The wrong version, it will lead to selenium does not work properly. So Chrome version before downloading please check the machine of their own.

chromedriver version Supported version of Chrome
v2.35 v62-64
v2.34 v61-63
v2.33 v60-62
v2.32 v59-61
v2.31 v58-60
v2.30 v58-60
v2.29 v56-58
v2.28 v55-57
v2.27 v54-56
v2.26 v53-55
v2.25 v53-55
v2.24 v52-54
v2.23 v51-53
v2.22 v49-52
v2.21 v46-50
v2.20 v43-48
v2.19 v43-47
v2.18 v43-46
v2.17 v42-43
v2.13 v42-45
v2.15 v40-43
v2.14 v39-42
v2.13 v38-41
v2.12 v36-40
v2.11 v36-40
v2.10 v33-36
v2.9 v31-34
v2.8 v30-33
v2.7 v30-33
v2.6 v29-32
v2.5 v29-32
v2.4 v29-32

3. Configure drive

将下载的ChromeDriver进行解压.
将解压后的文件放入合适的位置 将解压后的文件放入配置了环境变量的文件夹, 如python的文件夹,或者Chrome应用的文件夹中。

三、简单实用

  1. 导入模块
from selenium import werdriver
  1. 打开Chrome浏览器
driver = webdriver.Chrome()
  1. 输入网址
driver.get("https://XXXXX")
  1. 退出浏览器
driver.quit()
  1. 抓取页面元素
driver.find_element_by_id("id") #抓取id为“id”的元素

四、实战

废话不多说,直接上代码。实现一个简单的自动化打开百度的流程。

# -*- coding: utf-8 -*-

import time
from selenium import webdriver


def search_baidu():
    driver = webdriver.Chrome()
    # 最大化
    driver.maximize_window()
    # 打开百度
    driver.get("https://www.baidu.com")
    # 清空搜索框缓存内容
    driver.find_element_by_id("kw").clear()
    # 在搜索输入框中输入“自动化测试”
    driver.find_element_by_id("kw").send_keys(u"自动化测试")
    # 单击搜索按钮
    driver.find_element_by_id("su").click()
    # 等待5秒,以便查看结果
    time.sleep(5)
    # 退出浏览器
    driver.quit()


if __name__ == "__main__":
    search_baidu()

五、相关链接

如果想了解更多selenium框架的内容,可以查看selenium-python中文文档。这里有比较全面的知识点:
链接:selenium + python 中文文档

发布了19 篇原创文章 · 获赞 67 · 访问量 2万+

Guess you like

Origin blog.csdn.net/m1090760001/article/details/103132741