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连接sql server乱码的解决方法
Jan 28 Python
python用Pygal如何生成漂亮的SVG图像详解
Feb 10 Python
Python3.6通过自带的urllib通过get或post方法请求url的实例
May 10 Python
Python实现的读取电脑硬件信息功能示例
May 30 Python
python 实现语音聊天机器人的示例代码
Dec 02 Python
python开发准备工作之配置虚拟环境(非常重要)
Feb 11 Python
Django中信号signals的简单使用方法
Jul 04 Python
Python实现的微信红包提醒功能示例
Aug 22 Python
Python 70行代码实现简单算式计算器解析
Aug 30 Python
使用Python开发个京东上抢口罩的小实例(仅作技术研究学习使用)
Mar 10 Python
Python 实现一行输入多个数字(用空格隔开)
Apr 29 Python
Python实现Excel自动分组合并单元格
Feb 22 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
php is_file()和is_dir()用于遍历目录时用法注意事项
2010/03/02 PHP
PHP采用XML-RPC构造Web Service实例教程
2014/07/16 PHP
PHP中Memcache操作类及用法实例
2014/12/12 PHP
PHP实现提高SESSION响应速度的几种方法详解
2019/08/09 PHP
小议Function.apply()之二------利用Apply的参数数组化来提高 JavaScript程序性能
2006/11/30 Javascript
ExtJs Excel导出并下载IIS服务器端遇到的问题
2011/09/16 Javascript
基于dom编程中 动态创建与删除元素的使用
2013/04/17 Javascript
一个JS函数搞定网页标题(title)闪动效果
2014/05/13 Javascript
jquery得到iframe src属性值的方法
2014/09/25 Javascript
JS选中checkbox后获取table内一行TD所有数据的方法
2015/07/01 Javascript
js实现将选中值累加到文本框的方法
2015/08/12 Javascript
Bootstrap打造一个左侧折叠菜单的系统模板(一)
2016/05/17 Javascript
jQuery筛选数组之grep、each、inArray、map的用法及遍历json对象
2016/06/20 Javascript
easyui tree带checkbox实现单选的简单实例
2016/11/07 Javascript
JS实现选定指定HTML元素对象中指定文本内容功能示例
2017/02/13 Javascript
使用ef6创建oracle数据库的实体模型遇到的问题及解决方案
2017/11/09 Javascript
jQuery动态添加li标签并添加属性和绑定事件方法
2018/02/24 jQuery
Node.js 深度调试方法解析
2020/07/28 Javascript
[36:54]Mineski vs Winstrike 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
python编写的最短路径算法
2015/03/25 Python
python通过socket查询whois的方法
2015/07/18 Python
Python使用filetype精确判断文件类型
2017/07/02 Python
Python中XlsxWriter模块简介与用法分析
2018/04/24 Python
python生成密码字典的方法
2018/07/06 Python
Python字符串和正则表达式中的反斜杠('\')问题详解
2019/09/03 Python
python配置文件写入过程详解
2019/10/19 Python
django-orm F对象的使用 按照两个字段的和,乘积排序实例
2020/05/18 Python
聊聊python中的异常嵌套
2020/09/01 Python
python使用yaml 管理selenium元素的示例
2020/12/01 Python
加大码胸罩、内裤和服装:Just My Size
2019/03/21 全球购物
幼儿教师思想汇报
2014/01/10 职场文书
党员学习正风肃纪思想汇报
2014/09/12 职场文书
青年教师个人总结
2015/02/11 职场文书
房地产销售助理岗位职责
2015/04/14 职场文书
nginx实现动静分离的方法示例
2021/11/07 Servers
python周期任务调度工具Schedule使用详解
2021/11/23 Python