Python3.X使用Selenium驱动ChromeDriver自动化操作浏览器

来源:赵克立博客 分类: Python 标签:--发布时间:2018-01-28 17:46:25最后更新:2018-02-03 10:30:40浏览:5156
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2018-02-03 10:30:40
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

一、安装selenium

pip install selenium

二、下载谷歌和webdriver浏览器驱动文件

下载安装原生谷歌浏览器chrome.exe并且安装


下载webdriver驱动文件

https://sites.google.com/a/chromium.org/chromedriver/downloads

image.png

点开后选择

image.png

下载完成解压里面的webdrvier.exe到python的安装目录里,python的安装目录要加入系统的环境变量里

image.png

三、启动浏览器并打开指定网址

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
class AutoSearch():
    """docstring for AutoSearch"""
    def __init__(self):
        self.options = webdriver.ChromeOptions();
        #chrome 启动初始位置
        self.options.add_argument('--window-position=0,0');
        #chrome 启动初始大小
        self.options.add_argument('--window-size=1080,800');
        self.browser=webdriver.Chrome(chrome_options=self.options)
        self.browser.get("https://www.baidu.com")
obj=AutoSearch()

执行上面代码后就会打开百度首页面

image.png

四、使用selenium-webdriver提供的功能操作网页

一个完整的打开百度搜索python的功能 

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
class AutoSearch():
    """docstring for AutoSearch"""
    def __init__(self):
        self.options = webdriver.ChromeOptions();
        #chrome 启动初始位置
        self.options.add_argument('--window-position=0,0');
        #chrome 启动初始大小
        self.options.add_argument('--window-size=1080,800');
        self.browser=webdriver.Chrome(chrome_options=self.options)
        self.browser.get("http://www.sf-express.com/cn/sc/dynamic_function/waybill/#search/bill-number/964604199776")
    #通过id查找输入框输入文字
    def input_by_id(self, text=u"", element_id=""):
        #通过 id 查找网页元素
        input_el = self.browser.find_element_by_id(element_id)
        input_el.clear()
        #输入字符串
        input_el.send_keys(text)
        time.sleep(0.5)
    #通过id查找元素并单击
    def click_by_id(self, element_id=""):
        search_el = self.browser.find_element_by_id(element_id)
        #鼠标左键单击
        search_el.click()
        time.sleep(0.5)
    #通过类名查找元素并单击
    def click_by_class(self, element_class=""):
        #通过 class 查找网页元素
        search_el = self.browser.find_element_by_class_name(element_class)
        #鼠标左键单击
        search_el.click()
        time.sleep(0.5)
obj=AutoSearch()
obj.input_by_id('python','kw')
obj.click_by_id('su')

用法中文文档可以参考  http://selenium-python-docs-zh.readthedocs.io/zh_CN/latest/

英文文档 api    http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example


微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python