1.从QQ邮箱中导出通信录。(批量获取,可选)
选择“通讯录”→选择“工具”→选择以csv格式导出,这样就可以方便后续获取好友的QQ号码。
当然,如果通信录中显示的不是QQ邮箱,可以手工去除掉。
2.QQ空间说说的链接格式为:http://user.qzone.qq.com/{好友号码}/311,其中{好友号码}插入QQ号码即可。QQ空间说说首次打开需要登录,这里使用selenium+PhantomJS来实现。
爬取网址:http://user.qzone.qq.com/{好友号码}/311
爬取内容:好友说说,发表时间
存储方式:MongoDB或打印
from selenium import webdriver
import time
driver = webdriver.Chrome()
##driver = webdriver.PhantomJS()
driver.maximize_window()
driver.get("https://user.qzone.qq.com/XXX/311") #输入QQ号
driver.implicitly_wait(10)
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("账号") ##输入账号
driver.find_element_by_id("p").clear()
driver.find_element_by_id("p").send_keys("密码") ##输入密码
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")
contents = driver.find_elements_by_css_selector("pre.content")
times = driver.find_elements_by_css_selector("a.c_tx.c_tx3.goDetail")
for content,time in zip(contents,times):
print(content.text,time.text)
可以考虑加入批量获取QQ空间好友说说信息,MongoDB存储等。
代码如下:
from selenium import webdriver
from itertools import islice
import time
import csv
import pymongo
client = pymongo.MongoClient('localhost',27017) #连接数据库
mydb = client['mydb'] #新建mydb数据库
qq_s = mydb['qq_shuo'] #新建qq_shuo集合
driver = webdriver.Chrome()
#driver = webdriver.PhantomJS() #选择浏览器
driver.maximize_window()
def get_info(qq):
driver.get("https://user.qzone.qq.com/{}/311".format(qq))
driver.implicitly_wait(10)
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("XXXX")
driver.find_element_by_id("p").clear()
driver.find_element_by_id("p").send_keys("XXXX")
driver.find_element_by_id("login_button").click()
time.sleep(3)
driver.implicitly_wait(3) #登陆qq
try:
driver.find_element_by_id('QM_OwnerInfo_Icon')
b = True
except:
b = False
if b == True: #爬取内容模块
driver.switch_to_frame("app_canvas_frame")
contents = driver.find_elements_by_css_selector("pre.content")
times = driver.find_elements_by_css_selector("a.c_tx.c_tx3.goDetail")
for content,tim in zip(contents,times):
data = {
'内容':content.text,
'时间':tim.text
}
qq_s.insert_one(data) #使用insert_one插入数据
#print(content.text,tim.text)
if __name__== "__main__":
qq_lists=[]
with open("F:/QQmail.csv","r",encoding="utf-8") as f:
##方式一:
reader = csv.reader(f) #将数据变成列表
for row in islice(reader, 1, None): ##跳过第一行的数据
qq = row[2].split("@")[0]
qq_lists.append(qq)
## ##方式二:
## reader = csv.DictReader(f) #将数据变成字典
## for row in reader:
## qq = row['电子邮件'].split("@")[0]
## qq_lists.append(qq)
for qq in qq_lists:
get_info(qq)