python抓取搜狗微信公众号文章


Posted in Python onApril 01, 2019

初学python,抓取搜狗微信公众号文章存入mysql

mysql表:

python抓取搜狗微信公众号文章

python抓取搜狗微信公众号文章

代码:

import requests
import json
import re
import pymysql
 
# 创建连接
conn = pymysql.connect(host='你的数据库地址', port=端口, user='用户名', passwd='密码', db='数据库名称', charset='utf8')
# 创建游标
cursor = conn.cursor()

cursor.execute("select * from hd_gzh")
effect_row = cursor.fetchall()
from bs4 import BeautifulSoup

socket.setdefaulttimeout(60)
count = 1
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'}
#阿布云ip代理暂时不用
# proxyHost = "http-cla.abuyun.com"
# proxyPort = "9030"
# # 代理隧道验证信息
# proxyUser = "H56761606429T7UC"
# proxyPass = "9168EB00C4167176"

# proxyMeta = "http://%(user)s:%(pass)s@%(host)s:%(port)s" % {
#  "host" : proxyHost,
#  "port" : proxyPort,
#  "user" : proxyUser,
#  "pass" : proxyPass,
# }

# proxies = {
#   "http" : proxyMeta,
#   "https" : proxyMeta,
# }

#查看是否已存在数据
def checkData(name):
  sql = "select * from gzh_article where title = '%s'"
  data = (name,)
  count = cursor.execute(sql % data)
  conn.commit()
  if(count!=0):
    return False
  else:
    return True
#插入数据
def insertData(title,picture,author,content):
  sql = "insert into gzh_article (title,picture,author,content) values ('%s', '%s','%s', '%s')"
  data = (title,picture,author,content)
  cursor.execute(sql % data)
  conn.commit()
  print("插入一条数据")
  return
  
for row in effect_row:
  newsurl = 'https://weixin.sogou.com/weixin?type=1&s_from=input&query=' + row[1] + '&ie=utf8&_sug_=n&_sug_type_='
  res = requests.get(newsurl,headers=headers)
  res.encoding = 'utf-8'
  soup = BeautifulSoup(res.text,'html.parser')
  url = 'https://weixin.sogou.com' + soup.select('.tit a')[0]['href']
  res2 = requests.get(url,headers=headers)
  res2.encoding = 'utf-8'
  soup2 = BeautifulSoup(res2.text,'html.parser')
  pattern = re.compile(r"url \+= '(.*?)';", re.MULTILINE | re.DOTALL)
  script = soup2.find("script")
  url2 = pattern.search(script.text).group(1)
  res3 = requests.get(url2,headers=headers)
  res3.encoding = 'utf-8'
  soup3 = BeautifulSoup(res3.text,'html.parser')
  print()
  pattern2 = re.compile(r"var msgList = (.*?);$", re.MULTILINE | re.DOTALL)
  script2 = soup3.find("script", text=pattern2)
  s2 = json.loads(pattern2.search(script2.text).group(1))
  #等待10s
  time.sleep(10)
  
  for news in s2["list"]:
    articleurl = "https://mp.weixin.qq.com"+news["app_msg_ext_info"]["content_url"]
    articleurl = articleurl.replace('&','&')
    res4 = requests.get(articleurl,headers=headers)
    res4.encoding = 'utf-8'
    soup4 = BeautifulSoup(res4.text,'html.parser')
    if(checkData(news["app_msg_ext_info"]["title"])):
      insertData(news["app_msg_ext_info"]["title"],news["app_msg_ext_info"]["cover"],news["app_msg_ext_info"]["author"],pymysql.escape_string(str(soup4)))
    count += 1
    #等待5s
    time.sleep(10)
    for news2 in news["app_msg_ext_info"]["multi_app_msg_item_list"]:
      articleurl2 = "https://mp.weixin.qq.com"+news2["content_url"]
      articleurl2 = articleurl2.replace('&','&')
      res5 = requests.get(articleurl2,headers=headers)
      res5.encoding = 'utf-8'
      soup5 = BeautifulSoup(res5.text,'html.parser')
      if(checkData(news2["title"])):
        insertData(news2["title"],news2["cover"],news2["author"],pymysql.escape_string(str(soup5)))
      count += 1
      #等待10s
      time.sleep(10)
cursor.close()
conn.close()
print("操作完成")

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

Python 相关文章推荐
通过代码实例展示Python中列表生成式的用法
Mar 31 Python
Python虚拟环境Virtualenv使用教程
May 18 Python
python使用PyGame模块播放声音的方法
May 20 Python
Python PyQt5标准对话框用法示例
Aug 23 Python
python导出hive数据表的schema实例代码
Jan 22 Python
python将list转为matrix的方法
Dec 12 Python
python求最大值最小值方法总结
Jun 25 Python
利用Python库Scapy解析pcap文件的方法
Jul 23 Python
python中with语句结合上下文管理器操作详解
Dec 19 Python
如何使用 Python 读取文件和照片的创建日期
Sep 05 Python
Pandas DataFrame求差集的示例代码
Dec 13 Python
深度学习小工程练习之垃圾分类详解
Apr 14 Python
Python使用os.listdir()和os.walk()获取文件路径与文件下所有目录的方法
Apr 01 #Python
python装饰器简介---这一篇也许就够了(推荐)
Apr 01 #Python
Python批量删除只保留最近几天table的代码实例
Apr 01 #Python
Python中的Socket 与 ScoketServer 通信及遇到问题解决方法
Apr 01 #Python
python assert的用处示例详解
Apr 01 #Python
使用Python操作FTP实现上传和下载的方法
Apr 01 #Python
Python提取特定时间段内数据的方法实例
Apr 01 #Python
You might like
PDO防注入原理分析以及注意事项
2015/02/25 PHP
浅谈php fopen下载远程文件的函数
2016/11/18 PHP
PHP调试及性能分析工具Xdebug详解
2017/02/09 PHP
浅析php如何实现爬取数据原理
2018/09/27 PHP
Aster vs Newbee BO5 第三场2.19
2021/03/10 DOTA
javascript arguments 传递给函数的隐含参数
2009/08/21 Javascript
基于jquery的一个OutlookBar类,动态创建导航条
2010/11/19 Javascript
基于IE下ul li 互相嵌套时的bug,排查,解决过程以及心得介绍
2013/05/07 Javascript
Jquery创建一个层当鼠标移动到层上面不消失效果
2013/12/12 Javascript
jquery实现的鼠标下拉滚动置顶效果
2014/07/24 Javascript
nodejs中转换URL字符串与查询字符串详解
2014/11/26 NodeJs
JavaScript实现twitter puddles算法实例
2014/12/06 Javascript
使用JavaScript链式编程实现模拟Jquery函数
2014/12/21 Javascript
jquery实现textarea输入框限制字数的方法
2015/01/15 Javascript
js实现上传图片预览的方法
2015/02/09 Javascript
深入理解JavaScript系列(19):求值策略(Evaluation strategy)详解
2015/03/05 Javascript
javascript 面向对象function详解及实例代码
2017/02/28 Javascript
vue使用Axios做ajax请求详解
2017/06/07 Javascript
微信浏览器禁止页面下拉查看网址实例详解
2017/06/28 Javascript
VsCode与Node.js知识点详解
2019/09/05 Javascript
解决antd日期选择组件,添加value就无法点击下一年和下一月问题
2020/10/29 Javascript
详解python里使用正则表达式的分组命名方式
2017/10/24 Python
解决在Python编辑器pycharm中程序run正常debug错误的问题
2019/01/17 Python
python实现微信机器人: 登录微信、消息接收、自动回复功能
2019/04/29 Python
python爬虫 批量下载zabbix文档代码实例
2019/08/21 Python
Python中Flask-RESTful编写API接口(小白入门)
2019/12/11 Python
Python实现Kerberos用户的增删改查操作
2020/12/14 Python
Penhaligon’s英国官网:成立于1870年的英国香水制造商
2021/02/18 全球购物
设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
2014/12/30 面试题
研发工程师岗位职责
2014/04/28 职场文书
2014审计局领导班子民主生活会对照检查材料思想汇报
2014/09/20 职场文书
社区党建工作汇报材料
2014/10/27 职场文书
2014年残疾人工作总结
2014/12/06 职场文书
经费申请报告
2015/05/15 职场文书
导游词之西湖雷峰塔
2019/09/18 职场文书
Python中 range | np.arange | np.linspace三者的区别
2022/03/22 Python