网页抓取qq(存储1.安装Selenium分析网页结构说说的时间代码实现)

优采云 发布时间: 2021-12-25 05:08

  网页抓取qq(存储1.安装Selenium分析网页结构说说的时间代码实现)

  代码参考 /p/a6769dccd34d

  只需联系 Selenium,点击这里 Selenium 和 PhantomJS

  PS:代码的缺点是只能抓取第一页的内容。代码的改进是增加了与数据库的交互和存储。1.安装硒

  pip install Selenium

  2.Python中使用Selenium获取QQ空间小伙伴们的说说

  

  分析网页结构

  

  谈内容

  

  说话的时间

  

  3.代码实现(基于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)

#得到数据库

db = client['shuoshuo']

#得到一个数据集合

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

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

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插件,使用过程中会调用谷歌浏览器。如果写了绝对路径还是报错,请添加环境变量。

  

  

  通过 Robo 3T(强大的数据库 MongoDB 数据库管理工具),我们可以看到我们已经将数据库存储在了数据库中。

  接下来,我们应该用我们得到的数据做一些数据分析相关的事情……但我不会!!!

  正在努力学习数据分析...

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线