爬虫-selenium+HeadlessChrome

之前的笔记已经提到过selenium+chromedriver爬取Ajax技术加载的数据,但这种方式过于笨重,原因在于,每打开一个页面,都需要浏览器解析数据渲染界面,但实际上我们的爬虫不需要这些操作。所以一个没有界面但又完全可以模拟浏览器行为和获取与浏览器完全相同的数据就非常有意义,过去爬虫界流行的PhantomJS已经停止更新,并且新版的selenium目前已停止支持PhantomJS,所以现在替代方案为headless-Firefoxheadless-chrome(无头浏览器)

不多BB,谷歌大法好。

1. 浏览器处理步骤

1)处理HTML脚本,生成DOM树

2)处理CSS脚本,生成CSSOM树 (DOM和CSSOM是独立的数据结构)

3)将DOM树和CSSOM树合并为渲染树

4)对渲染树中的内容进行布局,计算每个节点的几何外观

5)将渲染树中的每个节点绘制到屏幕中

无头浏览器实际上节省了第4、5两个步骤。另外headeless-chrome还可以方便的实现并发,不多说了,直接上实战。

2. headless-chrome初体验

from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time chrome_options = Options()
chrome_options.add_argument("--headless") # 基础设置
chrome_options.add_argument('--disable-gpu')
base_url = "https://www.baidu.com/"
driver = webdriver.Chrome(executable_path=r'C:\Users\helloworld\Desktop\python_test\chromedriver.exe',options=chrome_options) # options必须设置,否则还是会打开界面 driver.get(base_url)
driver.find_element_by_id('kw').send_keys('python')
click = driver.find_element_by_id('su')
driver.execute_script('arguments[0].click()', click)
time.sleep(3) # 睡3秒是因为点击后需要等待一段时间,数据才会加载
driver.save_screenshot('baidu.png') # 从文件夹中打开baidu.png即可发现搜索python成功
driver.close()

因为现在爬虫的速度很快,前端的元素结构往往反应不过来,所以执行click操作时嵌入了JS脚本比较稳妥。

3. 实战爬取淘宝镇、街道信息

实际上无头浏览器的的代码操作与又界面的时候是完全一样的,唯一不同的是对无头浏览器的某些操作最好嵌入js代码执行,以防出现速度过快找不到元素。

# encoding: utf-8

'''
Created on 2018年1月5日 @author: wulinfeng@csdn博客
@date: 2018-1-5
''' import time
from selenium import webdriver
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
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
DRIVER = webdriver.Chrome(executable_path=r'C:\Users\helloworld\Desktop\python_test\chromedriver.exe',
chrome_options=chrome_options) def close_db():
CONNECTION.close() def close_web_driver():
DRIVER.quit() def login_taobao(username, password):
DRIVER.get("https://login.taobao.com/member/login.jhtml?spm=a21bo.2017.754894437.1.5af911d9fOuJW4&f=top&redirectURL=https%3A%2F%2Fwww.taobao.com%2F")
# 选择登陆方式
DRIVER.find_element_by_xpath("//div[@class='login-links']/a[1]").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) if __name__ == '__main__':
init_db()
init_web_driver()
login_taobao("用户名", "密码")
get_data()
close_db()
close_web_driver()

爬虫1.6-selenium+HeadlessChrome的更多相关文章

  1. python爬虫动态html selenium.webdriver

    python爬虫:利用selenium.webdriver获取渲染之后的页面代码! 1 首先要下载浏览器驱动: 常用的是chromedriver 和phantomjs chromedirver下载地址 ...

  2. scrapy爬虫框架和selenium的配合使用

    scrapy框架的请求流程 scrapy框架? Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架.因此Scrapy使用了一种非阻塞(又名异步)的 ...

  3. Python爬虫之设置selenium webdriver等待

    Python爬虫之设置selenium webdriver等待 ajax技术出现使异步加载方式呈现数据的网站越来越多,当浏览器在加载页面时,页面上的元素可能并不是同时被加载完成,这给定位元素的定位增加 ...

  4. # Python3微博爬虫[requests+pyquery+selenium+mongodb]

    目录 Python3微博爬虫[requests+pyquery+selenium+mongodb] 主要技术 站点分析 程序流程图 编程实现 数据库选择 代理IP测试 模拟登录 获取用户详细信息 获取 ...

  5. python3[爬虫实战] 使用selenium,xpath爬取京东手机

    使用selenium ,可能感觉用的并不是很深刻吧,可能是用scrapy用多了的缘故吧.不过selenium确实强大,很多反爬虫的都可以用selenium来解决掉吧. 思路: 入口: 关键字搜索入口 ...

  6. 爬虫基础(三)-----selenium模块应用程序

    摆脱穷人思维 <三> :  培养"目标导向"的思维:  好项目永远比钱少,只要目标正确,钱总有办法解决. 一 selenium模块 什么是selenium?seleni ...

  7. python爬虫之初始Selenium

    1.初始 Selenium[1]  是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Moz ...

  8. 爬虫_拉勾网(selenium)

    使用selenium进行翻页获取职位链接,再对链接进行解析 会爬取到部分空列表,感觉是网速太慢了,加了time.sleep()还是会有空列表 from selenium import webdrive ...

  9. 爬虫----爬虫请求库selenium

    一 介绍 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全模拟浏览器的操作, ...

  10. 爬虫请求库——selenium

    selenium模块 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题.selenium的缺点是效率会变得很慢. sel ...

随机推荐

  1. GoBelieve-国内唯一开源IM服务

    GoBelieve-国内唯一开源IM服务 1. 一小时接入 专注IM,无冗余功能 几行代码,一小时接入 省时省力. 2. 自由定制 提供最新源码, 自行二次开发,业务协议 交互视觉均可根据业务需求 自 ...

  2. 使用RMAN增量备份处理Dataguard因归档丢失造成的gap

    场景: 备库执行日志应用出现如下报错: Thu Mar 29 11:21:45 2018FAL[client]: Failed to request gap sequence GAP - thread ...

  3. iOS合并真机和模拟器framework

    在实际的项目开发中,我们会碰到某些静态库只能在真机或者模拟器中的一个上可以运行.为了让静态库在模拟器和真机都可以正常的运行,就涉及到如何把一个工程生成的静态库打包以后生成的framework进行合并. ...

  4. Core Data实例

    #import <UIKit/UIKit.h> #import <CoreData/CoreData.h> @interface CHViewController : UIVi ...

  5. iOS:UICollectionView流式布局及其在该布局上的扩展的线式布局

    UICollectionViewFlowLayout是苹果公司做好的一种单元格布局方式,它约束item的排列规则是:从左到右依次排列,如果右边不够放下,就换一行重复上面的方式排放,,,,,   常用的 ...

  6. ios下引用MUI后input不能输入,Android端正常

    原因是mui框架的有个css样式 *{ -webkit-user-select: none; } 其作用是禁掉用户可以选中页面中的内容. 添加以下style样式即可 input{ -webkit-us ...

  7. 微信小程序之数据传递

    本文主要介绍,页面跳转间的数据传递.传递的数据类型主要有1,基本数据类型:2,对象:3,数组集合: 先告诉你,本质上都是string类型传递.但是对于对象和数组集合的传递需要小小的处理一下传递时的数据 ...

  8. MySQL 参数slave_pending_jobs_size_max设置

    今天生产环境上从库出现SQL进程停止的异常,错误信息如下: Slave_IO_Running: Yes Slave_SQL_Running: No Replicate_Do_DB: Replicate ...

  9. python 两个面试题

    1.下面程序的运算结果是什么?? class Parent: def func(self): print("In Parent func") def __init__(self): ...

  10. python教程(三)·函数与模块

    函数,这和数学中的函数有点关联,但又不是完全等价 概念 不说的这么官方,我就已自己的理解来表达 ^_^ 在数学中,把一个或多个值(输入x)进行一定的计算或者映射,得到一个值(输出y),这个计算或者映射 ...