selenium+headless chrome爬虫的实现示例


Posted in Python onJanuary 08, 2021

      python爬虫写起来非常快,虽然也可以用java,但是没有python来的简洁迅速

      selenium在前面总结过,是一个自动化测试库。headless chrome是无界面的浏览器模式,和PHANTOMJS类似。但是PHANTOMJS往往会出现莫名的错误,而且速度没有headless chrome快

from selenium.webdriver.chrome.options import Options
 
global DRIVER
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
  
DRIVER = webdriver.Chrome(chrome_options=chrome_options)

        爬虫的代码有一点需要注意,需要操作事件的时候最好不要直接用相应的方法,比如click。最好嵌入js脚本的方式进行调用。因为爬虫的代码执行速度很快,前端元素结构往往反应不过来,从而找出元素不可见或者不存在的错误。

province_items = DRIVER.find_element_by_class_name("city-province").find_elements_by_tag_name("a")
 
#province_item.click()
DRIVER.execute_script('arguments[0].click();',province_item)

          下面来个例子,由于做电商平台,省、市、区的数据很好找,但是没有镇、街道的信息。这里通过爬虫从淘宝网将镇,街道的信息抓取下来

#! /usr/local/bin/python
# encoding: utf-8
 
'''
Created on 2018年1月5日
 
@author: wulinfeng
@date: 2018-1-5
'''
 
import time
#import request
from selenium import webdriver
#from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
import pymysql
 
def init_db():
  global CONNECTION 
  CONNECTION = pymysql.connect("地址","用户名","密码","数据库" ,use_unicode=True, charset="utf8")
 
def init_web_driver():
  global DRIVER
  #DRIVER = webdriver.PhantomJS(executable_path='C:\phantomjs-1.9.2-windows\phantomjs.exe')
  #DRIVER.set_window_size(1920, 1080)
  '''  
  dcap = dict(DesiredCapabilities.PHANTOMJS)
 
  dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36"
  )
  
  dcap["phantomjs.page.settings.viewportSize"] = (
    "width: 1920, "
    "height: 1080"
  )
  
  DRIVER = webdriver.PhantomJS(executable_path='C:\phantomjs-1.9.2-windows\phantomjs.exe',desired_capabilities=dcap)
  DRIVER.set_window_size(1920, 1080)
  '''
  
  chrome_options = Options()
  chrome_options.add_argument('--headless')
  chrome_options.add_argument('--disable-gpu')
  
  DRIVER = webdriver.Chrome(chrome_options=chrome_options)
  
  #DRIVER=webdriver.Ie()
  #DRIVER=webdriver.Chrome()
 
def close_db():
  CONNECTION.close()    
  
def close_web_driver():
  DRIVER.quit() 
  
def login_taobao(username, password):
  DRIVER.get("https://member1.taobao.com/member/fresh/deliver_address.htm?spm=a1z08.2.0.0.7dad47611Wnj46")
  #DRIVER.get("https://login.taobao.com/member/login.jhtml?spm=a21bo.2017.201864-2.d1.7d2082a4FxukGr&f=top&redirectURL=http%3A%2F%2Fwww.taobao.com%2F")
  #选择登陆方式
  DRIVER.find_element_by_xpath("//*[@id=\"J_Quick2Static\"]").click()
 
  #登陆
  input_user = DRIVER.find_element_by_xpath("//*[@id=\"TPL_username_1\"]")
  input_user.clear()
  input_user.send_keys(username)
  
  DRIVER.find_element_by_xpath("//*[@id=\"TPL_password_1\"]").send_keys(password)
  DRIVER.find_element_by_xpath("//*[@id=\"J_SubmitStatic\"]").click();
  
  time.sleep(0.5)
  
def get_data():
  #点击地址选择
  #DRIVER.find_element_by_xpath("//*[@id=\"city-title\"]").click()
  city_title = DRIVER.find_element_by_id("city-title")
  DRIVER.execute_script('arguments[0].click();',city_title)
  
  get_province_and_sub()
  
def get_province_and_sub():
  #获得省列表
  province_items = DRIVER.find_element_by_class_name("city-province").find_elements_by_tag_name("a")
  
  for province_item in province_items:
    pid = province_item.get_attribute("attr-id");
    pname = province_item.get_attribute("title");
    if pid == "-1":
      print("continue province")
      continue
    
    sql = "insert into region_province_t (province_id,province) values('"+pid+"','"+pname+"')"
    print(sql) 
    cursor = CONNECTION.cursor()
    cursor.execute(sql)
    CONNECTION.commit()
    
    #province_item.click()
    DRIVER.execute_script('arguments[0].click();',province_item)
    time.sleep(0.5)
    
    get_city_and_sub(pid)
    back_tab(0) 
  
def get_city_and_sub(pid):
  #获得市列表
  city_items = DRIVER.find_element_by_class_name("city-city").find_elements_by_tag_name("a")
  for city_item in city_items:
    cid = city_item.get_attribute("attr-id");
    cname = city_item.get_attribute("title");
    if cid == "-1":
      print("continue city")
      continue
  
    sql = "insert into region_city_t (city_id,city,province_id) values('"+cid+"','"+cname+"','"+pid+"')"
    print(sql) 
    cursor = CONNECTION.cursor()
    cursor.execute(sql)
    CONNECTION.commit()
    
    #city_item.click()
    DRIVER.execute_script('arguments[0].click();',city_item)
    time.sleep(1)
    
    get_area_and_sub(cid)
    back_tab(1)
    
def get_area_and_sub(cid):
  #获得县区列表
  area_items = DRIVER.find_element_by_class_name("city-district").find_elements_by_tag_name("a")
  for area_item in area_items:
    aid = area_item.get_attribute("attr-id");
    aname = area_item.get_attribute("title");
    if aid == "-1":
      print("continue area")
      continue
    
    sql = "insert into region_area_t (area_id,area,city_id) values('"+aid+"','"+aname+"','"+cid+"')"
    print(sql) 
    cursor = CONNECTION.cursor()
    cursor.execute(sql)
    CONNECTION.commit()
    
    #area_item.click()
    DRIVER.execute_script('arguments[0].click();',area_item)
    time.sleep(0.5)
    
    get_town_and_sub(aid)
    back_tab(2)
    
  
def get_town_and_sub(aid):
  #获得镇列表
  town_items = DRIVER.find_element_by_class_name("city-street").find_elements_by_tag_name("a")
  for town_item in town_items:
    tid = town_item.get_attribute("attr-id");
    tname = town_item.get_attribute("title");
    if tid == "-1":
      print("continue town")
      continue
    
    sql = "insert into region_town_t (town_id,town,area_id) values('"+tid+"','"+tname+"','"+aid+"')"
    print(sql) 
    cursor = CONNECTION.cursor()
    cursor.execute(sql)
    CONNECTION.commit()
    
def back_tab(index):
  districtEle = DRIVER.find_element_by_class_name("city-select-tab").find_elements_by_tag_name("a")[index]
  DRIVER.execute_script('arguments[0].click();',districtEle)
  time.sleep(0.5)
  
init_db()
init_web_driver()
login_taobao("用户名", "密码")
get_data()
close_db()
close_web_driver()

到此这篇关于selenium+headless chrome爬虫的实现示例的文章就介绍到这了,更多相关selenium+headless chrome爬虫内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木! 

Python 相关文章推荐
python生成器generator用法实例分析
Jun 04 Python
Using Django with GAE Python 后台抓取多个网站的页面全文
Feb 17 Python
Python学习教程之常用的内置函数大全
Jul 14 Python
python计算两个地址之间的距离方法
Jun 09 Python
Python3中正则模块re.compile、re.match及re.search函数用法详解
Jun 11 Python
Python Django 封装分页成通用的模块详解
Aug 21 Python
Pytorch中accuracy和loss的计算知识点总结
Sep 10 Python
Python socket模块方法实现详解
Nov 05 Python
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
Dec 04 Python
Python实现密码薄文件读写操作
Dec 16 Python
手动安装python3.6的操作过程详解
Jan 13 Python
Python 机器学习工具包SKlearn的安装与使用
May 14 Python
plt.figure()参数使用详解及运行演示
Jan 08 #Python
matplotlib绘制多子图共享鼠标光标的方法示例
Jan 08 #Python
利用python查看数组中的所有元素是否相同
Jan 08 #Python
Python爬虫自动化获取华图和粉笔网站的错题(推荐)
Jan 08 #Python
tensorflow与numpy的版本兼容性问题的解决
Jan 08 #Python
matplotlib自定义鼠标光标坐标格式的实现
Jan 08 #Python
selenium设置浏览器为headless无头模式(Chrome和Firefox)
Jan 08 #Python
You might like
新手菜鸟必读:session与cookie的区别
2013/08/22 PHP
详解PHP原生DOM对象操作XML的方法
2016/10/17 PHP
PHP读取文本文件并逐行输出该行使用最多的字符与对应次数的方法
2016/11/25 PHP
PHP高并发和大流量解决方案整理
2019/12/24 PHP
IE8 浏览器Cookie的处理
2009/01/31 Javascript
IE和firefox浏览器的event事件兼容性汇总
2009/12/06 Javascript
Textbox控件注册回车事件及触发按钮提交事件具体实现
2013/03/04 Javascript
jquery的live使用注意事项
2014/02/18 Javascript
javascript的回调函数应用示例
2014/02/20 Javascript
jquery text()方法取标签中的文本
2014/07/25 Javascript
纯Javascript实现ping功能的方法
2015/03/20 Javascript
TypeOf这些知识点你了解吗
2016/02/21 Javascript
JavaScript自学笔记(必看篇)
2016/06/23 Javascript
浅谈toLowerCase和toLocaleLowerCase的区别
2016/08/15 Javascript
微信小程序 购物车简单实例
2016/10/24 Javascript
vue实现添加标签demo示例代码
2017/01/21 Javascript
实现一个完整的Node.js RESTful API的示例
2017/09/29 Javascript
AngularJS使用ng-repeat遍历二维数组元素的方法详解
2017/11/11 Javascript
利用Javascript实现一套自定义事件机制
2017/12/14 Javascript
微信小程序 简易计算器实现代码实例
2019/09/02 Javascript
JS对日期操作封装代码实例
2019/11/08 Javascript
webpack+vue-cil 中proxyTable配置接口地址代理操作
2020/07/18 Javascript
一文读懂vue动态属性数据绑定(v-bind指令)
2020/07/20 Javascript
[01:03]悬念揭晓 11月26日DOTA2完美盛典不见不散
2017/11/23 DOTA
Python中的二叉树查找算法模块使用指南
2014/07/04 Python
Python中的Classes和Metaclasses详解
2015/04/02 Python
Python中的descriptor描述器简明使用指南
2016/06/02 Python
在python中实现强制关闭线程的示例
2019/01/22 Python
简单了解python中对象的取反运算符
2019/07/01 Python
结合OpenCV与TensorFlow进行人脸识别的实现
2019/10/10 Python
教育学习自我评价
2014/02/03 职场文书
优秀少先队辅导员先进事迹材料
2014/05/18 职场文书
2015新年联欢晚会开场白
2014/12/14 职场文书
三八红旗手事迹材料
2014/12/26 职场文书
化验室安全管理制度
2015/08/06 职场文书
python 如何用terminal输入参数
2021/05/25 Python