python爬虫之初恋 selenium

selenium 是一个web应用测试工具,能够真正的模拟人去操作浏览器。
用她来爬数据比较直观,灵活,和传统的爬虫不同的是,
她真的是打开浏览器,输入表单,点击按钮,模拟登陆,获得数据,样样行。完全不用考虑异步请求,所见即所得。

selenium语言方面支持java/python,浏览器方面支持各大主流浏览器谷歌,火狐,ie等。我选用的是python3.6+chrome组合


chrome

写python爬虫程序之前,需要准备两样东西:

1.[chrome][1]/浏览器              https://www.google.cn/chrome/
2.[chromedriver][2] /浏览器驱动   http://chromedriver.storage.googleapis.com/index.html

浏览器和浏览器驱动的搭配版本要求比较严格,不同的浏览器版本需要不同的驱动版本;我的版本信息:

 chrome info: chrome=66.0.3359.139
 Driver info: chromedriver=2.37.544315 

其他版本对照,浏览器驱动地址可直接根据浏览器版本下载对应驱动

chromedriver版本 Chrome版本
v2.37 v64-66
v2.36 v63-65
v2.34 v61-63

chrome浏览器
这里需要注意的是如果想更换对应的谷歌浏览器,要高版本的请务必直接升级处理,低版本的卸载时要彻底!彻底!彻底!卸载,包括(Google升级程序,注册表,残留文件等),再安装。否则爬虫程序启动不了浏览器。

chromedriver浏览器驱动
chromedriver 放置的位置也很重要,把chromedriver放在等会要写的.py文件旁边是最方便的方法。当然也可以不放这里,但是需要配置chromedriver的路径,我这里就不介绍这种方法了。

火狐驱动下载地址https://github.com/mozilla/ge...

python

终于开始敲代码了

打开网站

from selenium import webdriver

browser = webdriver.Chrome()
browser.get("https://segmentfault.com/")

三行代码即可自动完成启动谷歌浏览器,输出url,回车的骚操作。
此时的窗口地址栏下方会出现【Chrome 正在受到自动测试软件的控制】字样。

python爬虫之初恋 selenium_第1张图片

提交表单

下面我们来尝试控制浏览器输入并搜索关键字找到我们这篇文章;
先打开segmentfault网站,F12查看搜索框元素


发现是一个id为searchBox的input标签,ok

from selenium import webdriver
browser = webdriver.Chrome()   #打开浏览器
browser.get("https://segmentfault.com/")   #输入url

searchBox = browser.find_element_by_id("searchBox")  #通过id获得表单元素
searchBox.send_keys("python爬虫之初恋 selenium")   #向表单输入文字
searchBox.submit()    #提交

python爬虫之初恋 selenium_第2张图片

find_element_by_id()方法:根据id获得该元素。
同样还有其他方法比如

find_element_by_xpath() 通过路径选择元素
find_element_by_tag_name() 通过标签名获得元素
find_element_by_css_selector() 通过样式选择元素
find_element_by_class_name() 通过class获得元素
find_elements_by_class_name() 通过class获得元素们,element加s的返回的都是集合

举个栗子:

1.find_elements_by_css_selector("tr[bgcolor='#F2F2F2']>td")
  获得 style为 bgcolor='#F2F2F2' 的tr的子元素td

2.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/div[3]/div[1]/div[2]/div/h4/a")
  获得此路径下的a元素。
  find_element_by_xpath方法使用谷歌浏览器F12选择元素右键copy->copyXpath急速获得准确位置,非常好用,谁用谁知道
  
3.find_element_by_xpath("..")获得上级元素
4.find_element_by_xpath("following-sibling::")获同级下级元素
5.find_element_by_xpath("preceding-sibling::")获同级上级元素

抓取数据

获得元素后.text方法即可获得该元素的内容
我们获得文章的简介试试:

from selenium import webdriver
browser = webdriver.Chrome()   #打开浏览器

browser.get("https://segmentfault.com/")   #输入url
searchBox = browser.find_element_by_id("searchBox")  #通过id获得表单元素
searchBox.send_keys("python爬虫之初恋 selenium")   #向表单输入文字
searchBox.submit()                                #提交

text = browser.find_element_by_xpath("//*[@id='searchPage']/div[2]/div/div[1]/section/p[1]").text
print(text)

python爬虫之初恋 selenium_第3张图片

除了捕获元素还有其他操控浏览器的方法:

refresh() 刷新
click() 点击
close() 关闭当前标签页 (如果只有一个标签页就关闭浏览器)
quit() 关闭浏览器
title 获得当前页面的title
window_handles 获得所有窗口标签页id集合
current_window_handle 获得当前窗口标签页id
switch_to.window(【标签页id】) 根据选项卡id切换标签页
switch_to_frame("iframe的Id或name") 切换到iframe
switch_to.default_content() 切回最外层DOM
execute_script('window.open("www.segmentfault.com")') 执行js脚本(打开新标签)
maximize_window() 最大化
get_screenshot_as_file() 截图(图片保存路径+名称+后缀)
set_page_load_timeout(30) 设置加载时间
ActionChains(driver).move_to_element(ele).perform() 鼠标悬浮在ele元素上
value_of_css_property() 获得元素的样式(无论行内式还是内嵌式)
execute_script("return arguments[0].curentSrc;",【video元素】) 获得视频链接
execute_script("return arguments[0].duration;",【video元素】) 获得视频时长
execute_script("return arguments[0].play();",【video元素】) 播放视频
execute_script("return arguments[0].pause();",【video元素】) 暂停视频
启动前添加参数
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("--proxy-server=http://101.236.23.202:8866")  //代理
chromeOptions.add_argument("headless")   //不启动浏览器模式
browser = webdriver.Chrome(chrome_options=chromeOptions)
不加载图片启动
def openDriver_no_img():
    options = webdriver.ChromeOptions()
    prefs = {
        'profile.default_content_setting_values': {
            'images': 2
        }
    }
    options.add_experimental_option('prefs', prefs)
    browser = webdriver.Chrome(chrome_options=options)
    return browser
   

反爬虫应对手段

验证码识别:https://segmentfault.com/a/11...
IP代理:https://segmentfault.com/n/13...

你可能感兴趣的:(网页爬虫,python3.x)