爬虫-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. 将Tomcat设置为windows自动启动的服务

    一般情况下Tomcat服务需要手动运行批命令启动服务.在windows操作系统下如果需要将Tomcat变成自动启动的服务,只需按以下步骤操作即可: 方法/步骤 将Tomcat设置成服务(假设我们缺省的 ...

  2. python 输入一个整数,判断其是否既是3的倍数,又是5的倍数

    v = int(input('请输入一个整数:')) if v % 3 == 0 and v % 5 ==0: print(v,'即是3的倍数又是5的倍数') else: print('不是3或5的倍 ...

  3. DB数据源之SpringBoot+MyBatis踏坑过程(六)mysql中查看连接,配置连接数量

    DB数据源之SpringBoot+MyBatis踏坑过程(六)mysql中查看连接,配置连接数量 liuyuhang原创,未经允许禁止转载 系列目录连接 DB数据源之SpringBoot+Mybati ...

  4. 『ACM C++』 PTA 天梯赛练习集L1 | 044-45

    记录今日刷题 ------------------------------------------------L1-044--------------------------------------- ...

  5. linux安装完jenkins无法访问的问题

    jenkins是一个持续集成部署的工具,非常好用,当然,有些细节问题还是需要注意的.当我们兴高采烈的安装完jenkins的时候,然后发现并不能访问,真是气死了. 这个时候就要一步一步检测问题出在哪. ...

  6. 【读书笔记 - Effective Java】02. 遇到多个构造器参数时要考虑用构建器

    类有多个可选参数的解决方案: 1. 重叠构造器模式可行,但是当有许多参数的时候,客户端代码会很难编写,并且仍然较难以阅读. 2. JavaBeans模式,调用一个无参构造器来创造对象,然后调用sett ...

  7. thinkphp 5.1/tp5.1 route路由bug

    tp5.1下面RuleItem类中,match方法. 如果同一个控制器下面,写了两个路由,后一个路由比包含前一个路由,则访问后一个路由地址的时候,会跳转到前面定义的那个路由

  8. while 循环,格式化输出和运算编码

    今日内容 1.while循环 while Ture:             content = input ("请输入你要喷的内容",输入Q退出)             if ...

  9. Hive--关联表(join)

    在hive中,关联有4种方式: 内关联:join on 左外关联:left join on 右外关联:right join on 全外关联:full join on 另外还有一种可实现hive笛卡儿积 ...

  10. Zookeeper -- 本地\完全分布式 搭建

    准备工作 linux软件:Zookeeper-3.4.12.tar.gz 四台centos系统虚拟机,主机名为:s101~s104 一.本地模式搭建(s101上安装) 1.解压软件压缩包:解压到根目录 ...