获取qq好友发的说说

来源:互联网 发布:淘宝楼梯实木踏步板 编辑:程序博客网 时间:2024/05/10 08:31

一、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的使用。
我们需要爬取的页面时这样的:

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

from bs4 import BeautifulSoupfrom selenium import webdriverimport time#使用seleniumdriver = webdriver.PhantomJS(executable_path="D:\\phantomjs.exe")driver.maximize_window()#登录QQ空间def get_shuoshuo(qq):    driver.get('http://user.qzone.qq.com/{}/311'.format(qq))    time.sleep(5)    try:        driver.find_element_by_id('login_div')        a = True    except:        a = False    if a == True:        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)    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 = 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号')

获取到的部分数据截图如下:


接下来我们通过讲解代码,稍微了解一下Selenium的使用

三、代码简析
1.照例,导入需要使用的模块:

from bs4 import BeautifulSoupfrom selenium import webdriverimport 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_sourcesoup = 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代码")