Python爬虫实战:使用Selenium抓取QQ空间好友说说

时间:2023-03-09 19:19:33
Python爬虫实战:使用Selenium抓取QQ空间好友说说

前面我们接触到的,都是使用requests+BeautifulSoup组合对静态网页进行请求和数据解析,若是JS生成的内容,也介绍了通过寻找API借口来获取数据。

但是有的时候,网页数据由JS生成,API借口又死活找不着或者是API借口地址随机变换,时间不等人。那就只能使用Selenium了。

一、Selenium简介

Selenium是一个用于Web应用的功能自动化测试工具,Selenium 直接运行在浏览器中,就像真正的用户在操作一样。
由于这个性质,Selenium也是一个强大的网络数据采集工具,其可以让浏览器自动加载页面,获取需要的数据,甚至页面截图,或者是判断网站上某些动作是否发生。
Selenium自己不带浏览器,需要配合第三方浏览器来使用。支持的浏览器有Chrome、Firefox、IE、Phantomjs等。
如果使用Chrome、FireFox或IE,我们可以看得到一个浏览器的窗口被打开、打开网站、然后执行代码中的操作。
但是,让程序在后台中运行更符合我们爬虫的气质,所以自己多使用Phantomjs作为浏览器载体,本篇文章也以Phantomjs作介绍
Phantomjs是一个“无头”浏览器,也就是没有界面的浏览器,但是功能与普通的浏览器无异。

二、在Python中使用Selenium获取QQ空间好友说说

之前使用pip安装好了selenium,直接在代码中import即可。
下面我们以一个实际的例子——获取一个QQ空间好友的说说信息,来简单讲解一下Selenium+Phantomjs的使用。
我们需要爬取的页面时这样的:

Python爬虫实战:使用Selenium抓取QQ空间好友说说

QQ空间好友说说的链接为:http://user.qzone.qq.com/{好友QQ号}/311我们抓取他发的说说的时间和内容。

python3运行代码

  • 依旧先上代码:
 # -*- coding:utf-8 -*-
 from bs4 import BeautifulSoup
 from selenium import webdriver
 import time

 # #使用Selenium的webdriver实例化一个浏览器对象,在这里使用Phantomjs
 # driver = webdriver.PhantomJS(executable_path=r"D:\phantomjs-2.1.1-windows\bin\phantomjs.exe")
 # #设置Phantomjs窗口最大化
 # driver.maximize_window()

 # 登录QQ空间
 def get_shuoshuo(qq):
     chromedriver = r"D:\soft\chromedriver_win32\chromedriver.exe"
     driver = webdriver.Chrome(chromedriver)
     #使用get()方法打开待抓取的URL
     driver.get('http://user.qzone.qq.com/{}/311'.format(qq))
     time.sleep(5)
     #等待5秒后,判断页面是否需要登录,通过查找页面是否有相应的DIV的id来判断
     try:
         driver.find_element_by_id('login_div')
         a = True
     except:
         a = False
     if a == True:
         #如果页面存在登录的DIV,则模拟登录
         driver.switch_to.frame('login_frame')
         driver.find_element_by_id('switcher_plogin').click()
         driver.find_element_by_id('u').clear()  # 选择用户名框
         driver.find_element_by_id('u').send_keys('QQ号码')
         driver.find_element_by_id('p').clear()
         driver.find_element_by_id('p').send_keys('QQ密码')
         driver.find_element_by_id('login_button').click()
         time.sleep(3)
     driver.implicitly_wait(3)

     #判断好友空间是否设置了权限,通过判断是否存在元素ID:QM_OwnerInfo_Icon
     try:
         driver.find_element_by_id('QM_OwnerInfo_Icon')
         b = True
     except:
         b = False
     #如果有权限能够访问到说说页面,那么定位元素和数据,并解析
     if b == True:
         driver.switch_to.frame('app_canvas_frame')
         content = driver.find_elements_by_css_selector('.content')
         stime = driver.find_elements_by_css_selector('.c_tx.c_tx3.goDetail')
         for con, sti in zip(content, stime):
             data = {
                 'time': sti.text,
                 'shuos': con.text
             }
             print(data)
         pages = driver.page_source
         soup = BeautifulSoup(pages, 'lxml')

     #尝试一下获取Cookie,使用get_cookies()
     cookie = driver.get_cookies()
     cookie_dict = []
     for c in cookie:
         ck = "{0}={1};".format(c['name'], c['value'])
         cookie_dict.append(ck)
     i = ''
     for c in cookie_dict:
         i += c
     print('Cookies:', i)
     print("==========完成================")

     driver.close()
     driver.quit()

 if __name__ == '__main__':
     get_shuoshuo('好友QQ号码')

获取到的数据截图如下:

Python爬虫实战:使用Selenium抓取QQ空间好友说说

三、代码简析

1.照例,导入需要使用的模块:

from bs4 import BeautifulSoup
from selenium import webdriver
import time

2.使用Selenium的webdriver实例化一个浏览器对象,在这里使用Phantomjs:

driver = webdriver.PhantomJS(executable_path="D:\\phantomjs.exe")

3.设置Phantomjs窗口最大化:

driver.maximize_window()

4.主函数部分
使用get()方法打开待抓取的URL:

driver.get('http://user.qzone.qq.com/{}/311'.format(qq))

等待5秒后,判断页面是否需要登录,通过查找页面是否有相应的DIV的id来判断:

    try:
        driver.find_element_by_id('login_div')
        a = True
    except:
        a = False

如果页面存在登录的DIV,则模拟登录:

        driver.switch_to.frame('login_frame') #切换到登录ifram
        driver.find_element_by_id('switcher_plogin').click()
        driver.find_element_by_id('u').clear()#选择用户名框
        driver.find_element_by_id('u').send_keys('QQ号')
        driver.find_element_by_id('p').clear()#选择密码框
        driver.find_element_by_id('p').send_keys('QQ密码')
        driver.find_element_by_id('login_button').click()#点击登录按钮
        time.sleep(3)

接着,判断好友空间是否设置了权限,通过判断是否存在元素ID:QM_OwnerInfo_Icon

  try:
        driver.find_element_by_id('QM_OwnerInfo_Icon')
        b = True
    except:
        b = False

如果有权限能够访问到说说页面,那么定位元素和数据,并解析:

if b == True:
        driver.switch_to.frame('app_canvas_frame')
        content = driver.find_elements_by_css_selector('.content')
        stime = driver.find_elements_by_css_selector('.c_tx.c_tx3.goDetail')
        for con,sti in zip(content,stime):
            data = {
                # 'qq':qq,
                'time':sti.text,
                'shuos':con.text
            }
            print(data)

除了在Selenium中解析数据,我们还可以将当前页面保存为源码,再使用BeautifulSoup来解析:

pages = driver.page_source
soup = BeautifulSoup(pages,'lxml')

最后,我们尝试一下获取Cookie,使用get_cookies():

   cookie = driver.get_cookies()
    cookie_dict = []
    for c in cookie:
        ck = "{0}={1};".format(c['name'],c['value'])
        cookie_dict.append(ck)
    i = ''
    for c in cookie_dict:
        i += c
    print('Cookies:',i)

另外,再介绍两个Selenium的常用方法:

  • 保存屏幕截图:
driver.save_screenshot('保存的文件路径及文件名')
  • 执行JS脚本:
driver.execute_script("JS代码")

对于Selenium更加详细的操作和使用,推荐一本书《selenium webdriver(python)第三版》网上可以搜索到;