概述

在进行网站爬取数据的时候,会发现很多网站都进行了反爬虫的处理,如JS加密,Ajax加密,反Debug等方法,通过请求获取数据和页面展示的内容完全不同,这时候就用到Selenium技术,来模拟浏览器的操作,然后获取数据。本文以一个简单的小例子,简述Python搭配Tkinter和Selenium进行浏览器的模拟操作,仅供学习分享使用,如有不足之处,还请指正。

什么是Selenium?

Selenium 是一个用于Web应用程序测试的工具,Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。Selenium支持多种操作系统,如Windows、Linux、IOS等,如果需要支持Android,则需要特殊的selenium,本文主要以IE11浏览器为例。

安装Selenium

通过pip install selenium 进行安装即可,如果速度慢,则可以使用国内的镜像进行安装。

涉及知识点

程序虽小,除了需要掌握的Html ,JavaScript,CSS等基础知识外,本例涉及的Python相关知识点还是蛮多的,具体如下:

  • Selenium相关:

    • Selenium进行元素定位,主要有ID,Name,ClassName,Css Selector,Partial LinkText,LinkText,XPath,TagName等8种方式。
    • Selenium获取单一元素(如:find_element_by_xpath)和获取元素数组(如:find_elements_by_xpath)两种方式。
    • Selenium元素定位后,可以给元素进行赋值和取值,或者进行相应的事件操作(如:click)。
  • 线程(Thread)相关:
    • 为了防止前台页面卡主,本文用到了线程进行后台操作,如果要定义一个新的线程,只需要定义一个类并继承threading.Thread,然后重写run方法即可。
    • 在使用线程的过程中,为了保证线程的同步,本例用到了线程锁,如:threading.Lock()。
  • 队列(queue)相关:
    • 本例将Selenium执行的过程信息,保存到对列中,并通过线程输出到页面显示。queue默认先进先出方式。
    • 对列通过put进行压栈,通过get进行出栈。通过qsize()用于获取当前对列元素个数。
  • 日志(logging.Logger)相关:
    • 为了保存Selenium执行过程中的日志,本例用到了日志模块,为Pyhton自带的模块,不需要额外安装。
    • Python的日志共六种级别,分别是:NOTSET,DEBUG,INFO,WARN,ERROR,FATAL,CRITICAL。

示例效果图

本例主要针对某一配置好的商品ID进行轮询,监控是否有货,有货则加入购物车,无货则继续轮询,如下图所示:

核心代码

本例最核心的代码,就是利用Selenium进行网站的模拟操作,如下所示:

class Smoking:"""定义Smoking类"""# 浏览器驱动__driver: webdriver = None# 配置帮助类__cfg_info: dict = {}# 日志帮助类__log_helper: LogHelper = None# 主程序目录__work_path: str = ''# 是否正在运行__running: bool = False# 无货__no_stock = 'Currently Out of Stock'# 线程等待秒数__wait_sec = 2def __init__(self, work_path, cfg_info, log_helper: LogHelper):"""初始化"""self.__cfg_info = cfg_infoself.__log_helper = log_helperself.__work_path = work_pathself.__wait_sec = int(cfg_info['wait_sec'])# 如果小于2,则等于2self.__wait_sec = (2 if self.__wait_sec < 2 else self.__wait_sec)def checkIsExistsById(self, id):"""通过ID判断是否存在"""try:i = 0while self.__running and i < 3:if len(self.__driver.find_elements_by_id(id)) > 0:breakelse:time.sleep(self.__wait_sec)i = i + 1return len(self.__driver.find_elements_by_id(id)) > 0except BaseException as e:return Falsedef checkIsExistsByName(self, name):"""通过名称判断是否存在"""try:i = 0while self.__running and i < 3:if len(self.__driver.find_elements_by_name(name)) > 0:breakelse:time.sleep(self.__wait_sec)i = i + 1return len(self.__driver.find_elements_by_name(name)) > 0except BaseException as e:return Falsedef checkIsExistsByPath(self, path):"""通过xpath判断是否存在"""try:i = 0while self.__running and i < 3:if len(self.__driver.find_elements_by_xpath(path)) > 0:breakelse:time.sleep(self.__wait_sec)i = i + 1return len(self.__driver.find_elements_by_xpath(path)) > 0except BaseException as e:return Falsedef checkIsExistsByClass(self, cls):"""通过class名称判断是否存在"""try:i = 0while self.__running and i < 3:if len(self.__driver.find_elements_by_class_name(cls)) > 0:breakelse:time.sleep(self.__wait_sec)i = i + 1return len(self.__driver.find_elements_by_class_name(cls)) > 0except BaseException as e:return Falsedef checkIsExistsByLinkText(self, link_text):"""判断LinkText是否存在"""try:i = 0while self.__running and i < 3:if len(self.__driver.find_elements_by_link_text(link_text)) > 0:breakelse:time.sleep(self.__wait_sec)i = i + 1return len(self.__driver.find_elements_by_link_text(link_text)) > 0except BaseException as e:return Falsedef checkIsExistsByPartialLinkText(self, link_text):"""判断包含LinkText是否存在"""try:i = 0while self.__running and i < 3:if len(self.__driver.find_elements_by_partial_link_text(link_text)) > 0:breakelse:time.sleep(self.__wait_sec)i = i + 1return len(self.__driver.find_elements_by_partial_link_text(link_text)) > 0except BaseException as e:return False# def waiting(self, *locator):#     """等待完成"""#     # self.__driver.switch_to.window(self.__driver.window_handles[1])#     Wait(self.__driver, 60).until(EC.visibility_of_element_located(locator))def login(self, username, password):"""登录"""# 5. 点击链接跳转到登录页面self.__driver.find_element_by_link_text('账户登录').click()# 6. 输入账号密码# 判断是否加载完成# self.waiting((By.ID, "email"))if self.checkIsExistsById('email'):self.__driver.find_element_by_id('email').send_keys(username)self.__driver.find_element_by_id('password').send_keys(password)# 7. 点击登录按钮self.__driver.find_element_by_id('sign-in').click()def working(self, item_id):"""工作状态"""while self.__running:try:# 正常获取信息if self.checkIsExistsById('string'):self.__driver.find_element_by_id('string').clear()self.__driver.find_element_by_id('string').send_keys(item_id)self.__driver.find_element_by_id('string').send_keys(Keys.ENTER)# 判断是否查询到商品xpath = "//div[@class='specialty-header search']/div[@class='specialty-description']/div[" \"@class='gt-450']/span[2] "if self.checkIsExistsByPath(xpath):count = int(self.__driver.find_element_by_xpath(xpath).text)if count < 1:time.sleep(self.__wait_sec)self.__log_helper.put('没有查询到item id =' + item_id + '对应的信息')continueelse:time.sleep(self.__wait_sec)self.__log_helper.put('没有查询到item id2 =' + item_id + '对应的信息')continue# 判断当前库存是否有货xpath1 = "//div[@class='product-list']/div[@class='product']/div[@class='price-and-detail']/div[" \"@class='price']/span[@class='noStock'] "if self.checkIsExistsByPath(xpath1):txt = self.__driver.find_element_by_xpath(xpath1).textif txt == self.__no_stock:# 当前无货time.sleep(self.__wait_sec)self.__log_helper.put('查询一次' + item_id + ',无货')continue# 链接path1xpath2 = "//div[@class='product-list']/div[@class='product']/div[@class='imgDiv']/a"# 判断是否加载完毕# self.waiting((By.CLASS_NAME, "imgDiv"))if self.checkIsExistsByPath(xpath2):self.__driver.find_element_by_xpath(xpath2).click()time.sleep(self.__wait_sec)# 加入购物车if self.checkIsExistsByClass('add-to-cart'):self.__driver.find_element_by_class_name('add-to-cart').click()self.__log_helper.put('加入购物车成功,商品item-id:' + item_id)breakelse:self.__log_helper.put('未找到加入购物车按钮')else:self.__log_helper.put('没有查询到,可能是商品编码不对,或者已下架')except BaseException as e:self.__log_helper.put(e)def startRun(self):"""运行起来"""try:self.__running = Trueurl: str = self.__cfg_info['url']username = self.__cfg_info['username']password = self.__cfg_info['password']item_id = self.__cfg_info['item_id']if url is None or len(url) == 0 or username is None or len(username) == 0 or password is None or len(password) == 0 or item_id is None or len(item_id) == 0:self.__log_helper.put('配置信息不全,请检查config.cfg文件是否为空,然后再重启')returnif self.__driver is None:options = webdriver.IeOptions()options.add_argument('encoding=UTF-8')options.add_argument('Accept= text / css, * / *')options.add_argument('Accept - Language= zh - Hans - CN, zh - Hans;q = 0.5')options.add_argument('Accept - Encoding= gzip, deflate')options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko')# 2. 定义浏览器驱动对象self.__driver = webdriver.Ie(executable_path=self.__work_path + r'\IEDriverServer.exe', options=options)self.run(url, username, password, item_id)except BaseException as e:self.__log_helper.put('运行过程中出错,请重新打开再试')def run(self, url, username, password, item_id):"""运行起来"""# 3. 访问网站self.__driver.get(url)# 4. 最大化窗口self.__driver.maximize_window()if self.checkIsExistsByLinkText('账户登录'):# 判断是否登录:未登录self.login(username, password)if self.checkIsExistsByPartialLinkText('欢迎回来'):# 判断是否登录:已登录self.__log_helper.put('登录成功,下一步开始工作了')self.working(item_id)else:self.__log_helper.put('登录失败,请设置账号密码')def stop(self):"""停止"""try:self.__running = False# 如果驱动不为空,则关闭self.close_browser_nicely(self.__driver)if self.__driver is not None:self.__driver.quit()# 关闭后切要为None,否则启动报错self.__driver = Noneexcept BaseException as e:print('Stop Failure')finally:self.__driver = Nonedef close_browser_nicely(self, browser):try:browser.execute_script("window.onunload=null; window.onbeforeunload=null")except Exception as err:print("Fail to execute_script:'window.onunload=null; window.onbeforeunload=null'")socket.setdefaulttimeout(10)try:browser.quit()print("Close browser and firefox by calling quit()")except Exception as err:print("Fail to quit from browser, error-type:%s, reason:%s" % (type(err), str(err)))socket.setdefaulttimeout(30)

其他辅助类

日志类(LogHelper),代码如下:

class LogHelper:"""日志帮助类"""__queue: queue.Queue = None  # 队列__logging: logging.Logger = None  # 日志__running: bool = False  # 是否记录日志def __init__(self, log_path):"""初始化类"""self.__queue = queue.Queue(1000)self.init_log(log_path)def put(self, value):"""添加数据"""# 记录日志self.__logging.info(value)# 添加到队列if self.__queue.qsize() < self.__queue.maxsize:self.__queue.put(value)def get(self):"""获取数据"""if self.__queue.qsize() > 0:try:return self.__queue.get(block=False)except BaseException as e:return Noneelse:return Nonedef init_log(self, log_path):"""初始化日志"""self.__logging = logging.getLogger()self.__logging.setLevel(logging.INFO)# 日志rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))log_name = log_path + rq + '.log'logfile = log_name# if not os.path.exists(logfile):#     # 创建空文件#     open(logfile, mode='r')fh = logging.FileHandler(logfile, mode='a', encoding='UTF-8')fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关# 第三步,定义handler的输出格式formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")fh.setFormatter(formatter)# 第四步,将logger添加到handler里面self.__logging.addHandler(fh)def get_running(self):# 获取当前记录日志的状态return self.__runningdef set_running(self, v: bool):# 设置当前记录日志的状态self.__running = v

配置类(ConfigHelper)

class ConfigHelper:"""初始化数据类"""__config_dir = None__dic_cfg = {}def __init__(self, config_dir):"""初始化"""self.__config_dir = config_dirdef ReadConfigInfo(self):"""得到配置项"""parser = ConfigParser()parser.read(self.__config_dir + r"\config.cfg")section = parser.sections()[0]items = parser.items(section)self.__dic_cfg.clear()for item in items:self.__dic_cfg.__setitem__(item[0], item[1])def getConfigInfo(self):"""获取配置信息"""if len(self.__dic_cfg) == 0:self.ReadConfigInfo()return self.__dic_cfg

线程类(MyThread)

class MyThread(threading.Thread):"""后台监控线程"""def __init__(self, tid, name, smoking: Smoking, log_helper: LogHelper):"""线程初始化"""threading.Thread.__init__(self)self.threadID = tidself.name = nameself.smoking = smokingself.log_helper = log_helperdef run(self):print("开启线程: " + self.name)self.log_helper.put("开启线程: " + self.name)# 获取锁,用于线程同步# lock = threading.Lock()# lock.acquire()self.smoking.startRun()# 释放锁,开启下一个线程# lock.release()print("结束线程: " + self.name)self.log_helper.put("结束线程: " + self.name)

备注

侠客行  [唐:李白]

赵客缦胡缨,吴钩霜雪明。银鞍照白马,飒沓如流星。
十步杀一人,千里不留行。事了拂衣去,深藏身与名。
闲过信陵饮,脱剑膝前横。将炙啖朱亥,持觞劝侯嬴。
三杯吐然诺,五岳倒为轻。眼花耳热后,意气素霓生。
救赵挥金槌,邯郸先震惊。千秋二壮士,烜赫大梁城。
纵死侠骨香,不惭世上英。谁能书阁下,白首太玄经。

Python利用Selenium模拟浏览器自动操作相关推荐

  1. python下selenium模拟浏览器常见操作

    本文主要记录下selenium的常见操作,如定位具体元素的不同方法.在具体元素内循环.提取文本等.具体代码如下: # -*- coding: utf-8 -*- ''' Created on 2019 ...

  2. Python+BeautifulSoup+Selenium模拟浏览器循环自动播放视频,如哔哩哔哩某个UP主的视频

    1.前言 计算机的出现,推动了人类社会的进步,使得人们更高效的工作或是生活.当我们很"懒"的时候,计算机就能站出来,帮助我们做一些我们觉得浪费时间的事情了.你嫌用手点鼠标麻烦,计算 ...

  3. python模拟浏览器下载文件在哪里_python下selenium模拟浏览器基础操作

    1.安装及下载 selenium安装: pip install selenium  即可自动安装selenium geckodriver下载:https://github.com/mozilla/ge ...

  4. c++浏览器自动化操作_精:C# 利用Selenium实现浏览器自动化操作

    概述 Selenium是一款免费的分布式的自动化测试工具,支持多种开发语言,无论是C. java.ruby.python.或是C# ,你都可以通过selenium完成自动化测试.本文以一个简单的小例子 ...

  5. Python使用selenium模拟浏览器爬取某查查数据

    在使用爬虫爬取某查查的数据的时候,会被识别到,进行反爬限制,最后使用selenium模拟浏览器进行爬取. 这里解决办法主要使用selenium打开浏览器,模拟人操作进行爬取,代码: ua = 'Moz ...

  6. 利用python加selenium模拟浏览器爬取百度爱企查企业详细信息

    目录 说明 企查查网页构成方式 代码与详解 说明 本人不是什么爬虫大佬,只是最近在做一个项目的时候需要根据企业的名称把企业的信息爬取下来,例如营业执照.工商注册号等.在网上找了很多的信息与资源,都不是 ...

  7. python利用selenium模拟登陆163邮箱

    首先需要定位登录框的地址,分析过程见 https://www.jianshu.com/p/d59a5611c053 登陆框标签是一个iframe,且id每次都是不一样的,因此不能按id值查找,这里先按 ...

  8. python 模拟浏览器selenium 微信_Spider-Python爬虫之使用Selenium模拟浏览器行为

    分析 他的代码比较简单,主要有以下的步骤:使用BeautifulSoup库,打开百度贴吧的首页地址,再解析得到id为new_list标签底下的img标签,最后将img标签的图片保存下来. header ...

  9. python 模拟浏览器selenium_python爬虫:使用Selenium模拟浏览器行为

    前几天有位微信读者问我一个爬虫的问题,就是在爬去百度贴吧首页的热门动态下面的图片的时候,爬取的图片总是爬取不完整,比首页看到的少.原因他也大概分析了下,就是后面的图片是动态加载的.他的问题就是这部分动 ...

最新文章

  1. Excel信息提取之二
  2. 关于启动 SecureCRT 遇到一个致命的错误且必须关闭
  3. ICDAR 2019论文:自然场景文字定位技术详解
  4. python 变量类型list_Python基础变量类型——List浅析-阿里云开发者社区
  5. 巴赛尔协议与贷款产品利率解析
  6. 华为指标OceanStore
  7. Android仿人人客户端(v5.7.1)——对从服务器端(网络)获取的图片进行本地双缓存处理(编码实现)...
  8. 移动存储设备数据卡和闪存盘等半导体存储式设备,数据消失被格式化,如何拯救恢复?
  9. Linux中文件查找方法大全
  10. 计算机操作系统(第四版)课后习题答案西电版V2.0校对版
  11. 孪生网络keras实现minist
  12. 24、将Div中的所有元素保存为图片 Html2Canvas
  13. 标识符 关键字 字面值 数据类型 进制换算 字符编码 变量 数据类型详解 运算符
  14. 微信小程序分析送积分功能如何实现_微信小程序如何建立积分系统?
  15. 机器学习中【回归算法】详解
  16. windows rt是什么系统
  17. 7-13 查找奥运五环色的位置 (10分)
  18. 所属技术领域技术人员的知识和能力
  19. 心跳计算机游戏,聪明人才能玩的游戏 解谜游戏《心跳 Heartbeats》讲述
  20. 保护8亿终端 阿里聚安全携手信通院打造B2C资金安全闭环 1

热门文章

  1. 2023PS beta 官方注册安装教程
  2. 使用Tensorboard绘制网络识别准确率和loss曲线
  3. [bzoj1143][二分图匹配]祭祀
  4. [轻笔记]numpy拟合曲线并求导
  5. 安全HCIP之AAA
  6. 逐步攻略:使用Matlab音频系统工具箱创建自己的VST插件,让音乐编程在Nashville崭新绽放
  7. 【斐波那契LDPC】基于斐波那契序列的QC-LDPC改进,译码采用LLR-BP译码算法
  8. B站百万收藏,超强学习法:我用过之后,强烈推荐给你们
  9. 百度云同步盘登录失败,报错155010的问题解决
  10. zotero+坚果云实现同步