python爬虫爬取微信_Python爬虫爬取微信小程序
之前打算做个微信小程序的社区,所以写了爬虫去爬取微信小程序,后面发现做微信小程序没有前途,就把原来的项目废弃了做了现在的网站观点,不过代码放着也是放着,还不如公开让大家用,所以我把代码贴出来,有需要的复制了使用就是了。
#coding:utf-8
__author__ = 'haoning'
#!/usr/bin/env python
import time
import urllib2
import datetime
import requests
import json
import random
import sys
import platform
import uuid
reload(sys)
sys.setdefaultencoding( "utf-8" )
import re
import os
import MySQLdb as mdb
from bs4 import BeautifulSoup
DB_HOST = '127.0.0.1'
DB_USER = 'root'
DB_PASS = 'root'
#init database
conn = mdb.connect(DB_HOST, DB_USER, DB_PASS, 'pybbs-springboot', charset='utf8')
conn.autocommit(False)
curr = conn.cursor()
count=0
how_many=0
base_url='http://www.wechat-cloud.com'
url=base_url+"/index.php?s=/home/article/ajax_get_list.html&category_id={category_id}&page={page}&size={size}"
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 chrome_6494_1.html' target='_blank'>Chrome/16.0.912.77 Safari/535.7",
"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 ",
]
def fake_header():
agent=random.choice(user_agents)
cookie='PHPSESSID=p5mokvec7ct1gqe9efcnth9d44; Hm_lvt_c364957e96174b029f292041f7d822b7=1487492811,1487556626; Hm_lpvt_c364957e96174b029f292041f7d822b7=1487564069'
req_header = {
'Accept':'application/json, text/javascript, */*; q=0.01',
#'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Host':'www.wechat-cloud.com',
#'Cookie':cookie,
'Referer':'http://www.wechat-cloud.com/index.php?s=/home/index/index.html',
'Upgrade-Insecure-Requests':'1',
'User-Agent':agent,
'X-Requested-With':'XMLHttpRequest',
}
return req_header
def gethtml(url):
try:
header=fake_header()
req = urllib2.Request(url,headers=header)
response = urllib2.urlopen(req, None,15)
html = response.read()
return html
except Exception as e:
print "e",e
return None
def get_img_data(url):
try:
#添加头信息,模仿浏览器抓取网页,对付返回403禁止访问的问题
req = urllib2.Request(url)
response = urllib2.urlopen(req, None,15)
dataimg = response.read()
return dataimg
except Exception as e:
print "image data",e
return None
def makeDateFolder(par,classify):
try:
if os.path.isdir(par):
newFolderName=par + '//' + str(classify)+ "//" +GetDateString()
if not os.path.isdir( newFolderName ):
os.makedirs( newFolderName )
return newFolderName
else:
return par
except Exception,e:
print "kk",e
return par
def map_folder(what):
return what
def GetDateString():
when=time.strftime('%Y-%m-%d',time.localtime(time.time()))
foldername = str(when)
return foldername
def get_extension(name):
where=name.rfind('.')
if where!=-1:
return name[where:len(name)]
return "#"
def download_img(url,what):
try:
#print url
extention=get_extension(url)
dataimg=get_img_data(url)
name=str(uuid.uuid1()).replace('-','')+"-www.weixinapphome.com"
#print "name",name
classfiy_folder=map_folder(what)
top="E://wxapp_store"
filename =makeDateFolder(top,classfiy_folder)+"//"+name+extention
try:
if not os.path.exists(filename):
file_object = open(filename,'w+b')
file_object.write(dataimg)
file_object.close()
return classfiy_folder+"/"+GetDateString()+"/"+name+extention
else:
print "file exist"
return None
except IOError,e1:
print "e1=",e1
#pass
return None #如果没有下载下来就利用原来网站的链接
except Exception,e:
print "problem",e
pass
return None
def work():
page=0
global how_many
while 1:
try:
page=page+1
begin_url=url.format(category_id=0, page=page,size=12).encode('utf-8')
html=gethtml(begin_url)
if html is not None:
#print html
json_results=json.loads(html)
is_end=json_results['isEnd']
if str(is_end)=="True":
break
results=json_results['list']
for result in results:
href=result['href']
detail_url=base_url+href
#print detail_url
detail_html=gethtml(detail_url)
if detail_html is not None:
soup = BeautifulSoup(detail_html)
icon_url=base_url+soup.find('div',{'class':'icon fl'}).find('img').get('src')
name=soup.find('div',{'class':'cont fl'}).find('h2').text
classify=soup.find('div',{'class':'tab'}).find('span').text
classify=str(classify).replace("分类: ","")
#print classify
barcode_path=base_url+soup.find('div',{'id':'install-code'}).find('img').get('src')
view_num=soup.find('span',{'class':'views'}).text
#view_num=filter(str.isalnum,str(view_num))
pic_path=base_url+soup.find('div',{'class':'img-box'}).find('img').get('src')
temp = time.time()
x = time.localtime(float(temp))
acq_time = time.strftime("%Y-%m-%d %H:%M:%S",x) # get time now
curr.execute('select id from pybbs_wxapp_store where `from`=%s',(detail_url))
y= curr.fetchone()
if not y:
y1=download_img(icon_url,"icon")
y2=download_img(barcode_path,"barcode")
y3=download_img(pic_path,"pic")
if (y1 is not None) and (y2 is not None) and (y3 is not None):
name=name
author=None
classify=classify
describe=None
view_num=view_num
#print view_num
logo=y1
_from=detail_url
barcode=y2
acq_time=acq_time
hot_weight=-9999
pic_uuid=str(uuid.uuid1()).replace('-','')
pic_path=y3
#print name,author,classify,describe,view_num,logo,_from,barcode,acq_time,hot_weight,pic_uuid
curr.execute('INSERT INTO pybbs_wxapp_store(name,author,classify,`describe`,view_num,logo,`from`,barcode,acq_time,hot_weight,pic_path)VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',(name,author,classify,describe,view_num,logo,_from,barcode,acq_time,hot_weight,pic_path))
curr.execute('select id from pybbs_wxapp_classify where `classify_name`=%s',(classify))
yx= curr.fetchone()
if not yx:
describe=None
temp = time.time()
x = time.localtime(float(temp))
record_time = time.strftime("%Y-%m-%d %H:%M:%S",x) # get time now
curr.execute('INSERT INTO pybbs_wxapp_classify(classify_name,`describe`,record_time)VALUES(%s,%s,%s)',(classify,describe,record_time))
how_many+=1
print "new comer:",pic_uuid,">>",how_many
if how_many % 10==0:
conn.commit()
conn.commit()
except Exception as e:
print "while error",e
if __name__ == '__main__':
i=3
while i>0:
work()
i=i-1
其中有些参数请改成自己的,比如说数据库密码了,图片存储到哪个盘,数据库表格自己建立,因为这些实在太简单了,所以没啥可以唠叨的。
标签: 微信
顶一下
(0)
0%
踩一下
(0)
0%
python爬虫爬取微信_Python爬虫爬取微信小程序相关推荐
- python计算bmi的编程_Python学习-计算BMI的小程序
示例: 小明身高1.75,体重80.5kg.请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:低于18.5:过轻 18.5-25:正常 25-28:过重 28-32:肥 ...
- 小程序素材抓取_到底要不要做百度小程序
百度近两年动作不断,针对搜索流量,频繁推出MIP.熊掌号.小程序三款产品,分别对标谷歌AMP.微信公众号和微信小程序.至于说效果,前两款对于网站流量提升和标准化用户体验都有明显帮助,也部分提高了国内搜 ...
- 脱离微信,在硬件设备运行小程序?小程序硬件框架大揭秘!
受访者 | 微信小程序硬件框架团队 采访者 | 伍杏玲 出品 | CSDN(ID:CSDNnews) 在 2017 年的微信公开课 PRO 上,张小龙谈到微信小程序的设计初衷:"我认为所有的 ...
- 挑战微信、试探苹果?支付宝小程序可添加到 iOS 手机桌面
点击上方"CSDN",选择"置顶公众号" 关键时刻,第一时间送达! [CSDN编者按]从微信小程序到快应用,移动互联网正面临着一场重新洗牌.以往的应用分发模式已 ...
- 通过微信模板消息跳转到小程序
关注小编微信公众号公众号[前端基础教程从0开始]回复"1",拉你进程序员技术讨论群,群内有大神,可以免费提供问题解答.公众号回复"小程序",领取300个优秀的小 ...
- c语言编程微信公众号图片直播,如何以图片的形式在微信公众号文章中添加小程序...
如何以图片的形式在微信公众号文章中添加小程序 微信公众号中想要将自己的小程序也放进去,宣传宣传,该怎么添加?下面百分网小编带大家一起来看看详细操作教程,感兴趣的朋友一起学习吧!!!想了解更多相关信息请 ...
- 直击微信公开课:2019年小程序将会有哪些改变?
又是一年一度的微信公开课 PRO,犹记去年,张小龙曾说小程序是微信期望最大的项目,而在过去的一年中,百度.支付宝.头条小程序接连上线,对微信小程序进行围攻,对此,微信在新的一年会如何反击?来看Info ...
- URL Scheme-短信、邮件、微信外网页等场景打开小程序
URL Scheme--适用于从短信.邮件.微信外网页等场景打开小程序. 通过 URL Scheme 打开小程序的场景值为 1065. 生成的 URL Scheme 如下所示: weixin://dl ...
- 首发全DIY强大微信朋友圈截图制作生成小程序源码下载点赞,评论等等
这是一款朋友圈截图制作的一款小程序源码 主要的特点是DIY,之前小编发布过朋友圈截图的小程序 不管之前那款小程序只能生成点赞数量,无法获取用户名等等 但是这一款就不一样了,这一款刚刚也说了特点是DIY ...
- DIY微信朋友圈截图制作生成小程序源码下载
这是一款朋友圈截图制作的一款小程序源码 主要的特点是DIY,之前小编发布过朋友圈截图的小程序 不管之前那款小程序只能生成点赞数量,无法获取用户名等等 但是这一款就不一样了,这一款刚刚也说了特点是DIY ...
最新文章
- 脑网络的可塑性——随时都在发生
- layer,一个可以让你想到即可做到的javascript弹窗(层)解决方案
- [机器学习] Coursera ML笔记 - 逻辑回归(Logistic Regression)
- Jenkins 持续集成自动化测试配置
- android 获取当前网络,Android 获取当前网络连接的类型信息
- 更新Composer依赖报错处理Fatal error: Declaration of Fxp\Composer\AssetPlugin\Repository\AbstractAssetsRe...
- python消息中间件activemq_消息中间件ActiveMQ和JMS基础
- filters.revealTrans.Transition用法
- 微信小程序:配置合法域名
- vue.js 首屏优化
- android开源播放器代码,github上十二款最著名的Android播放器开源项目
- Axure RP 8.1最新激活码
- java命名规则及规范
- 消息中间件:简述消息队列(MessageQueue)
- html页面背景图片不够大怎么办,Word背景图片不够大怎么办
- CDH安装过程中出现:主机 cdh04 上的内存被调拨过度。总内存分配额是 4.0 艾字节 个字节,但是 RAM 只有 62.8 吉字节 个字节(其中的 12.6 吉字节 个字节是保留给系统使用的)。
- 英语AquilariaCrassna奇楠沉香
- Android进阶——巧借自定义VideoView实现Activity的动态视频背景
- MySQL对数据表进行分组查询(GROUP BY)
- 图像超分:HAN(Single Image Super-Resolution via a Holistic Attention Network)