Python selenium抓取微博内容的示例代码


Posted in Python onMay 17, 2018

Selenium简介与安装

Selenium是什么?

Selenium也是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE、Mozilla Firefox、Mozilla Suite等。

安装

直接使用pip命令安装即可!

pip install selenium

Python抓取微博有两种方式,一是通过selenium自动登录后从页面直接爬取,二是通过api。

这里采用selenium的方式。

程序:

from selenium import webdriver
import time
import re
#全局变量
driver = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")

def loginWeibo(username, password):
  driver.get('https://passport.weibo.cn/signin/login')
  time.sleep(1)

  driver.find_element_by_id("loginName").send_keys("haishu_zheng@163.com")
  driver.find_element_by_id("loginPassword").send_keys("Weibo01061122")

  time.sleep(1)
  driver.find_element_by_id("loginAction").click()

  #driver.close()
  
def visitUserPage(userId):
  driver.get('http://weibo.cn/' + userId)

  print('********************')  
  print('用户资料')
  
  # 1.用户id
  print('用户id:' + userId)
  
  # 2.用户昵称
  strName = driver.find_element_by_xpath("//div[@class='ut']")
  strlist = strName.text.split(' ')
  nickname = strlist[0]
  print('昵称:' + nickname)
  
  # 3.微博数、粉丝数、关注数
  strCnt = driver.find_element_by_xpath("//div[@class='tip2']")
  pattern = r"\d+\.?\d*" # 匹配数字,包含整数和小数
  cntArr = re.findall(pattern, strCnt.text)
  print(strCnt.text)
  print("微博数:" + str(cntArr[0]))
  print("关注数:" + str(cntArr[1]))
  print("粉丝数:" + str(cntArr[2]))
  
  print('\n********************')
  # 4.将用户信息写到文件里
  with open("weibo.txt", "w", encoding = "gb18030") as file:
    file.write("用户ID:" + userId + '\r\n')
    file.write("昵称:" + nickname + '\r\n')
    file.write("微博数:" + str(cntArr[0]) + '\r\n')
    file.write("关注数:" + str(cntArr[1]) + '\r\n')
    file.write("粉丝数:" + str(cntArr[2]) + '\r\n')
    
  # 5.获取微博内容
  # http://weibo.cn/ + userId + ? filter=0&page=1
  # filter为0表示全部,为1表示原创
  print("微博内容")
  
  pageList = driver.find_element_by_xpath("//div[@class='pa']")
  print(pageList.text)
  pattern = r"\d+\d*"     # 匹配数字,只包含整数
  pageArr = re.findall(pattern, pageList.text)
  totalPages = pageArr[1]   # 总共有多少页微博
  print(totalPages)
  
  pageNum = 1     # 第几页
  numInCurPage = 1      # 当前页的第几条微博内容
  contentPath = "//div[@class='c'][{0}]"
  while(pageNum <= 3):  
  #while(pageNum <= int(totalPages)):
    contentUrl = "http://weibo.cn/" + userId + "?filter=0&page=" + str(pageNum)
    driver.get(contentUrl)
    content = driver.find_element_by_xpath(contentPath.format(numInCurPage)).text
    # print("\n" + content) # 微博内容,包含原创和转发
    if "设置:皮肤.图片.条数.隐私" not in content:
      numInCurPage += 1
      with open("weibo.txt", "a", encoding = "gb18030") as file:
        file.write("\r\n" + "\r\n" + content)  # 将微博内容逐条写到weibo.txt中
    else:
      pageNum += 1            # 抓取新一页的内容
      numInCurPage = 1          # 每一页都是从第1条开始抓    
    
if __name__ == '__main__':
  username = 'haishu_zheng@163.com'  # 输入微博账号
  password = 'Weibo01061122'     # 输入密码
  loginWeibo(username, password)   # 要先登录,否则抓取不了微博内容
  time.sleep(3)
  uid = 'xywyw'            # 寻医问药
  visitUserPage(uid)

运行结果:

Python selenium抓取微博内容的示例代码

同时还生成了weibo.txt文件,内容如下

Python selenium抓取微博内容的示例代码

这种方法有个缺陷,就是爬取较多内容会被封IP:

Python selenium抓取微博内容的示例代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python显示天气预报
Mar 02 Python
python中的函数用法入门教程
Sep 02 Python
python实现用于测试网站访问速率的方法
May 26 Python
Python基于有道实现英汉字典功能
Jul 25 Python
python实现二叉查找树实例代码
Feb 08 Python
python 中if else 语句的作用及示例代码
Mar 05 Python
python实现简单成绩录入系统
Sep 19 Python
python3实现raspberry pi(树莓派)4驱小车控制程序
Feb 12 Python
Pytorch转onnx、torchscript方式
May 25 Python
Python 创建守护进程的示例
Sep 29 Python
python 如何设置守护进程
Oct 29 Python
Django自定义YamlField实现过程解析
Nov 11 Python
Python实现的查询mysql数据库并通过邮件发送信息功能
May 17 #Python
Python实现读取txt文件并转换为excel的方法示例
May 17 #Python
cmd运行python文件时对结果进行保存的方法
May 16 #Python
Python基于lxml模块解析html获取页面内所有叶子节点xpath路径功能示例
May 16 #Python
Python使用Dijkstra算法实现求解图中最短路径距离问题详解
May 16 #Python
Python基于Floyd算法求解最短路径距离问题实例详解
May 16 #Python
Python使用selenium实现网页用户名 密码 验证码自动登录功能
May 16 #Python
You might like
重置版宣传动画
2020/04/09 魔兽争霸
PHPMailer 中文使用说明小结
2010/01/22 PHP
基于php iconv函数的使用详解
2013/06/09 PHP
php使用百度翻译api示例分享
2014/01/31 PHP
Yii调试SQL的常用方法
2014/07/09 PHP
Linux下手动编译安装PHP扩展的例子分享
2014/07/15 PHP
PHP获取当前URL路径的处理方法(适用于多条件筛选列表)
2017/02/10 PHP
Jquery Change与bind事件代码
2011/09/29 Javascript
JS TextArea字符串长度限制代码集合
2012/10/31 Javascript
解决jquery1.9不支持browser对象的问题
2013/11/13 Javascript
js控制网页前进和后退的方法
2015/06/08 Javascript
jQuery.trim() 函数及trim()用法详解
2015/10/26 Javascript
js 提交form表单和设置form表单请求路径的实现方法
2016/10/25 Javascript
Angular自定义组件实现数据双向数据绑定的实例
2017/12/11 Javascript
vue页面切换到滚动页面显示顶部的实例
2018/03/13 Javascript
vsCode安装使用教程和插件安装方法
2020/08/24 Javascript
微信小程序实现简单跑马灯效果
2020/05/26 Javascript
vue+Element实现搜索关键字高亮功能
2019/05/28 Javascript
vue 获取视频时长的实例代码
2019/08/20 Javascript
python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍
2016/09/21 Python
利用Python库Scapy解析pcap文件的方法
2019/07/23 Python
8段用于数据清洗Python代码(小结)
2019/10/31 Python
python中openpyxl和xlsxwriter对Excel的操作方法
2021/03/01 Python
布里斯班女装时尚品牌:Adrift
2017/12/28 全球购物
日本必酷网络直营店:Biccamera
2019/03/23 全球购物
任课老师推荐信范文
2013/11/24 职场文书
开展党的群众路线教育实践活动方案
2014/02/05 职场文书
2014年学校办公室工作总结
2014/12/19 职场文书
大学生在校表现评语
2014/12/31 职场文书
推荐信范文大全
2015/03/27 职场文书
2015年中秋晚会主持稿
2015/07/30 职场文书
师德师风心得体会(2016精选篇)
2016/01/12 职场文书
写作技巧:如何撰写商业计划书
2019/08/08 职场文书
Android studio 简单计算器的编写
2022/05/20 Java/Android
Python实现双向链表基本操作
2022/05/25 Python
Python中的协程(Coroutine)操作模块(greenlet、gevent)
2022/05/30 Python