代碼參考http://www.itdecent.cn/p/a6769dccd34d
剛接觸Selenium的戳這里Selenium與PhantomJS
PS:代碼的不足在于只能抓取第一頁的說說內(nèi)容,代碼的改進之處在于增加了與數(shù)據(jù)庫的交互,進行了存儲
1.安裝Selenium
pip install Selenium
2.在Python中使用Selenium獲取QQ空間好友說說

分析網(wǎng)頁結構

說說內(nèi)容

發(fā)表說說的時間

3.代碼實現(xiàn)(基于Python3)
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pymongo
# #使用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):
#建立與MongoClient的鏈接
client = pymongo.MongoClient('localhost', 27017)
#得到數(shù)據(jù)庫
db = client['shuoshuo']
#得到一個數(shù)據(jù)集合
sheet_tab = db['sheet_tab']
chromedriver = r"E:\mycode\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
#如果有權限能夠訪問到說說頁面,那么定位元素和數(shù)據(jù),并解析
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)
sheet_tab.insert_one(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)
driver.close()
driver.quit()
if __name__ == '__main__':
get_shuoshuo('好友的QQ號')
注意:使用前記得安裝chromedriver這個插件,使用的過程中會呼起一個谷歌瀏覽器。如果寫了絕對路徑還報錯的話,就加入環(huán)境變量。


通過Robo 3T(數(shù)據(jù)庫MongoDB的一款功能強大的數(shù)據(jù)庫管理工具)可以看到我們已經(jīng)將拿到的數(shù)據(jù)庫存儲于數(shù)據(jù)庫中
接下來我們應該通過拿到的數(shù)據(jù)做一些數(shù)據(jù)分析...可是我不會!??!
正在努力學習數(shù)據(jù)分析中.....
如果你覺得我的文章還可以,可以關注我的微信公眾號:Python攻城獅

可掃描二維碼,添加關注