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 正则表达式操作指南
May 04 Python
python列表操作使用示例分享
Feb 21 Python
Python3中多线程编程的队列运作示例
Apr 16 Python
在Python中用split()方法分割字符串的使用介绍
May 20 Python
Python 的描述符 descriptor详解
Feb 27 Python
分享6个隐藏的python功能
Dec 07 Python
python 的 openpyxl模块 读取 Excel文件的方法
Sep 09 Python
python二元表达式用法
Dec 04 Python
Tensorflow轻松实现XOR运算的方式
Feb 03 Python
python学生管理系统的实现
Apr 05 Python
基于python实现检索标记敏感词并输出
May 07 Python
python爬虫基础知识点整理
Jun 02 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
《超神学院》霸气归来, 天使彦上演维多利亚的秘密
2020/03/02 国漫
php检测iis环境是否支持htaccess的方法
2014/02/18 PHP
解决phpcms更换javascript的幻灯片代码调用图片问题
2014/12/26 PHP
php读取flash文件高宽帧数背景颜色的方法
2015/01/06 PHP
PHP设计模式之模板模式定义与用法详解
2018/12/20 PHP
PDO::prepare讲解
2019/01/29 PHP
PHP超低内存遍历目录文件和读取超大文件的方法
2019/05/01 PHP
php实现快速对二维数组某一列进行组装的方法小结
2019/12/04 PHP
详解Javascript动态操作CSS
2014/12/08 Javascript
jQuery EasyUI Pagination实现分页的常用方法
2016/05/21 Javascript
移动端jQuery修正Web页面滑动时div问题的两则实例
2016/05/30 Javascript
JS 验证密码 不能为空,必须含有数字、字母、特殊字符,长度在8-12位
2017/06/21 Javascript
Vue.js与 ASP.NET Core 服务端渲染功能整合
2017/11/16 Javascript
jQuery图片加载失败替换默认图片方法汇总
2017/11/29 jQuery
如何使node也支持从url加载一个module详解
2018/06/05 Javascript
Vue form表单动态添加组件实战案例
2019/09/02 Javascript
Vuex的各个模块封装的实现
2020/06/05 Javascript
node脚手架搭建服务器实现token验证的方法
2021/01/20 Javascript
[02:36]DOTA2混沌骑士 英雄基础教程
2013/11/26 DOTA
Python 处理数据的实例详解
2017/08/10 Python
Python内存管理方式和垃圾回收算法解析
2017/11/11 Python
python unittest实现api自动化测试
2018/04/04 Python
Python获取命令实时输出-原样彩色输出并返回输出结果的示例
2019/07/11 Python
解决TensorFlow GPU版出现OOM错误的问题
2020/02/03 Python
python读取与处理netcdf数据方式
2020/02/14 Python
使用python-cv2实现视频的分解与合成的示例代码
2020/10/26 Python
jupyter notebook快速入门及使用详解
2020/11/13 Python
python3中编码获取网页的实例方法
2020/11/16 Python
CSS3绘制有活力的链接下划线
2016/07/14 HTML / CSS
GUESS西班牙官方网上商城:美国服饰品牌
2017/03/15 全球购物
Zatchels官网:英国剑桥包品牌
2021/01/12 全球购物
食品工程专业求职信
2014/06/15 职场文书
幼儿园老师新年寄语2015
2014/12/08 职场文书
保留意见审计报告
2015/06/05 职场文书
python 如何做一个识别率百分百的OCR
2021/05/29 Python
Nginx文件已经存在全局反向代理问题排查记录
2022/07/15 Servers