python爬蟲微信朋友圈
❶ 如何用 Python 爬自己的微信朋友
首先,在終端安裝一下itchat包。
pip install itchat
安裝完成後導入包,再登陸自己的微信。過程中會生產一個登陸二維碼,掃碼之後即可登陸。登陸成功後,把自己好友的相關信息爬下來。
import itchat
itchat.login()
#爬取自己好友相關信息, 返回一個json文件
friends = itchat.get_friends(update=True)[0:]
有了上面的friends數據,我們就可以來做分析啦。
1. 自己微信好友的男女比例
仔細觀察了一下返回的數據結構,發現」性別「是存放在一個字典裡面的,key是」Sex「,男性值為1,女性為2,其他是不明性別的(就是沒有填的)。可以寫個循環獲取想要的性別數據,得到自己微信好友的性別比例。
#初始化計數器
male = female = other = 0
#friends[0]是自己的信息,所以要從friends[1]開始
for i in friends[1:]:
sex = i["Sex"]
if sex == 1:
male += 1
elif sex == 2:
female += 1
else:
other +=1
#計算朋友總數
total = len(friends[1:])
#列印出自己的好友性別比例
print("男性好友: %.2f%%" % (float(male)/total*100) + "n" +
"女性好友: %.2f%%" % (float(female) / total * 100) + "n" +
"不明性別好友: %.2f%%" %(float(other) / total * 100))
列印的結果為:
男性好友: 37.65%
女性好友: 59.23%
不明性別好友: 3.12%
❷ python爬取微信好友運動步數
微信分享的url本身就有openid,偽造Request Headers然後拿到返回的信息就行了
❸ 如何利用Python爬取微信運動中各個好友的運動信息
可以測試一下
#!/usr/bin/python3
""" This script simulate a PC wechat client to get wechat sports data """
import re
import json
import requests
# Headers: simulate wechat embedded browser
HEADERS = {
'Connection': 'keep-alive',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501'
' NetType/WIFI WindowsWechat QBCore/3.43.27.400 QQBrowser/9.0.2524.400',
'Accept-Encoding': 'gzip, deflate'
}
COOKIES = {
'hwstepranksk': '填入Cookie',
'pass_ticket': '填入Cookie'
}
REQUEST_URL = ''
def get_info(openid):
"""Get data according to openid"""
params = {"openid": openid}
data = requests.get(url=REQUEST_URL, params=params, cookies=COOKIES, headers=HEADERS)
data.encoding = "utf-8"
try:
return parse_code(data.text)
except LookupError:
return {"Error": "Cookies could be out of date"}
def parse_code(code):
"""Parse web page source code"""
match_strings = re.findall(r"window.json = (\S+);", code)
# json strings are hided in js code
if len(match_strings) == 0:
raise LookupError
else:
json_string = match_strings[0]
json_object = json.loads(json_string)
data_dict = {
"openid": json_object.get("myopenid"),
"Today Steps": json_object.get("rankdesc").get("score"),
"History Steps": json_object.get("rankdetaillist")[0].get("score"),
"Highest Record": json_object.get("rankdetaillist")[1].get("score")
}
return data_dict
if __name__ == "__main__":
print(get_info("o95gOt0QsJ4O4vxBVUzmYeXGuN74"))
❹ 如何利用Python網路爬蟲抓取微信好友數量以及
可以用wxpy模塊來
❺ 如何用python爬微信群或者公眾號
首先,你要知道.read處理出來的是什麼東西
我們能讀取伺服器響應的內容。再次以 GitHub 時間線為例:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/.
Requests 會自動解碼來自伺服器的內容。大多數 unicode 字元集都能被無縫地解碼。
返回的是解碼過的數據,自然不是直接寫入二進制文件中.
❻ python爬取微信好朋友圈怎麼實現
有一個微信網頁版.模擬登陸是可以登陸上去的.但是看不了朋友圈.只能通過手機的方式進行爬取了.
❼ python怎麼抓取微信閱
抓取微信公眾號的文章
一.思路分析
目前所知曉的能夠抓取的方法有:
1、微信APP中微信公眾號文章鏈接的直接抓取(http://mp.weixin.qq.com/s?__biz=MjM5MzU4ODk2MA==&mid=2735446906&idx=1&sn=&scene=0#rd)
2、通過微信合作方搜狗搜索引擎(http://weixin.sogou.com/),發送相應請求來間接抓取
第1種方法中,這種鏈接不太好獲取,而且他的規律不是特別清晰。
因此本文採用的是方法2----通過給 weixin.sogou.com 發送即時請求來實時解析抓取數據並保存到本地。
二.爬取過程
1、首先在搜狗的微信搜索頁面測試一下,這樣能夠讓我們的思路更加清晰
在搜索引擎上使用微信公眾號英文名進行「搜公眾號」操作(因為公眾號英文名是公眾號唯一的,而中文名可能會有重復,同時公眾號名字一定要完全正確,不然可能搜到很多東西,這樣我們可以減少數據的篩選工作,只要找到這個唯一英文名對應的那條數據即可),即發送請求到'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_= ' % 'python',並從頁面中解析出搜索結果公眾號對應的主頁跳轉鏈接。
2.獲取主頁入口內容
使用request , urllib,urllib2,或者直接使用webdriver+phantomjs等都可以
這里使用的是request.get()的方法獲取入口網頁內容
[python]view plain
#爬蟲偽裝頭部設置
self.headers={'User-Agent':'Mozilla/5.0(WindowsNT6.3;WOW64;rv:51.0)Gecko/20100101Firefox/51.0'}
#設置操作超時時長
self.timeout=5
#爬蟲模擬在一個request.session中完成
self.s=requests.Session()
#搜索入口地址,以公眾為關鍵字搜索該公眾號
defget_search_result_by_keywords(self):
self.log('搜索地址為:%s'%self.sogou_search_url)
returnself.s.get(self.sogou_search_url,headers=self.headers,timeout=self.timeout).content
#獲得公眾號主頁地址
defget_wx_url_by_sougou_search_html(self,sougou_search_html):
doc=pq(sougou_search_html)
#printdoc('p[class="tit"]')('a').attr('href')
#printdoc('div[class=img-box]')('a').attr('href')
#通過pyquery的方式處理網頁內容,類似用beautifulsoup,但是pyquery和jQuery的方法類似,找到公眾號主頁地址
returndoc('div[class=txt-box]')('p[class=tit]')('a').attr('href')
#使用webdriver載入公眾號主頁內容,主要是js渲染的部分
defget_selenium_js_html(self,url):
browser=webdriver.PhantomJS()
browser.get(url)
time.sleep(3)
#執行js得到整個頁面內容
html=browser.execute_script("returndocument.documentElement.outerHTML")
returnhtml
#獲取公眾號文章內容
defparse_wx_articles_by_html(self,selenium_html):
doc=pq(selenium_html)
print'開始查找內容msg'
returndoc('div[class="weui_media_boxappmsg"]')
#有的公眾號僅僅有10篇文章,有的可能多一點
#returndoc('div[class="weui_msg_card"]')#公眾號只有10篇文章文章的
#!/usr/bin/python
#coding:utf-8
importsys
reload(sys)
sys.setdefaultencoding('utf-8')
fromurllibimportquote
frompyqueryimportPyQueryaspq
fromseleniumimportwebdriver
importrequests
importtime
importre
importjson
importos
classweixin_spider:
def__init__(self,kw):
'構造函數'
self.kw=kw
#搜狐微信搜索鏈接
#self.sogou_search_url='http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_='%quote(self.kw)
self.sogou_search_url='http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_='%quote(self.kw)
#爬蟲偽裝
self.headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;WOW64;rv:47.0)Gecko/20100101FirePHP/0refox/47.0FirePHP/0.7.4.1'}
#操作超時時長
self.timeout=5
self.s=requests.Session()
defget_search_result_by_kw(self):
self.log('搜索地址為:%s'%self.sogou_search_url)
returnself.s.get(self.sogou_search_url,headers=self.headers,timeout=self.timeout).content
defget_wx_url_by_sougou_search_html(self,sougou_search_html):
'根據返回sougou_search_html,從中獲取公眾號主頁鏈接'
doc=pq(sougou_search_html)
#printdoc('p[class="tit"]')('a').attr('href')
#printdoc('div[class=img-box]')('a').attr('href')
#通過pyquery的方式處理網頁內容,類似用beautifulsoup,但是pyquery和jQuery的方法類似,找到公眾號主頁地址
returndoc('div[class=txt-box]')('p[class=tit]')('a').attr('href')
defget_selenium_js_html(self,wx_url):
'執行js渲染內容,並返回渲染後的html內容'
browser=webdriver.PhantomJS()
browser.get(wx_url)
time.sleep(3)
#執行js得到整個dom
html=browser.execute_script("returndocument.documentElement.outerHTML")
returnhtml
defparse_wx_articles_by_html(self,selenium_html):
'從selenium_html中解析出微信公眾號文章'
doc=pq(selenium_html)
returndoc('div[class="weui_msg_card"]')
defswitch_arctiles_to_list(self,articles):
'把articles轉換成數據字典'
articles_list=[]
i=1
ifarticles:
forarticleinarticles.items():
self.log(u'開始整合(%d/%d)'%(i,len(articles)))
articles_list.append(self.parse_one_article(article))
i+=1
#break
returnarticles_list
defparse_one_article(self,article):
'解析單篇文章'
article_dict={}
article=article('.weui_media_box[id]')
title=article('h4[class="weui_media_title"]').text()
self.log('標題是:%s'%title)
url='http://mp.weixin.qq.com'+article('h4[class="weui_media_title"]').attr('hrefs')
self.log('地址為:%s'%url)
summary=article('.weui_media_desc').text()
self.log('文章簡述:%s'%summary)
date=article('.weui_media_extra_info').text()
self.log('發表時間為:%s'%date)
pic=self.parse_cover_pic(article)
content=self.parse_content_by_url(url).html()
contentfiletitle=self.kw+'/'+title+'_'+date+'.html'
self.save_content_file(contentfiletitle,content)
return{
'title':title,
'url':url,
'summary':summary,
'date':date,
'pic':pic,
'content':content
}
defparse_cover_pic(self,article):
'解析文章封面圖片'
pic=article('.weui_media_hd').attr('style')
p=re.compile(r'background-image:url(.∗?)')
rs=p.findall(pic)
self.log('封面圖片是:%s'%rs[0]iflen(rs)>0else'')
returnrs[0]iflen(rs)>0else''
defparse_content_by_url(self,url):
'獲取文章詳情內容'
page_html=self.get_selenium_js_html(url)
returnpq(page_html)('#js_content')
defsave_content_file(self,title,content):
'頁面內容寫入文件'
withopen(title,'w')asf:
f.write(content)
defsave_file(self,content):
'數據寫入文件'
withopen(self.kw+'/'+self.kw+'.txt','w')asf:
f.write(content)
deflog(self,msg):
'自定義log函數'
printu'%s:%s'%(time.strftime('%Y-%m-%d%H:%M:%S'),msg)
defneed_verify(self,selenium_html):
'有時候對方會封鎖ip,這里做一下判斷,檢測html中是否包含id=verify_change的標簽,有的話,代表被重定向了,提醒過一陣子重試'
returnpq(selenium_html)('#verify_change').text()!=''
defcreate_dir(self):
'創建文件夾'
ifnotos.path.exists(self.kw):
os.makedirs(self.kw)
defrun(self):
'爬蟲入口函數'
#Step0:創建公眾號命名的文件夾
self.create_dir()
#Step1:GET請求到搜狗微信引擎,以微信公眾號英文名稱作為查詢關鍵字
self.log(u'開始獲取,微信公眾號英文名為:%s'%self.kw)
self.log(u'開始調用sougou搜索引擎')
sougou_search_html=self.get_search_result_by_kw()
#Step2:從搜索結果頁中解析出公眾號主頁鏈接
self.log(u'獲取sougou_search_html成功,開始抓取公眾號對應的主頁wx_url')
wx_url=self.get_wx_url_by_sougou_search_html(sougou_search_html)
self.log(u'獲取wx_url成功,%s'%wx_url)
#Step3:Selenium+PhantomJs獲取js非同步載入渲染後的html
self.log(u'開始調用selenium渲染html')
selenium_html=self.get_selenium_js_html(wx_url)
#Step4:檢測目標網站是否進行了封鎖
ifself.need_verify(selenium_html):
self.log(u'爬蟲被目標網站封鎖,請稍後再試')
else:
#Step5:使用PyQuery,從Step3獲取的html中解析出公眾號文章列表的數據
self.log(u'調用selenium渲染html完成,開始解析公眾號文章')
articles=self.parse_wx_articles_by_html(selenium_html)
self.log(u'抓取到微信文章%d篇'%len(articles))
#Step6:把微信文章數據封裝成字典的list
self.log(u'開始整合微信文章數據為字典')
articles_list=self.switch_arctiles_to_list(articles)
#Step7:把Step5的字典list轉換為Json
self.log(u'整合完成,開始轉換為json')
data_json=json.mps(articles_list)
#Step8:寫文件
self.log(u'轉換為json完成,開始保存json數據到文件')
self.save_file(data_json)
self.log(u'保存完成,程序結束')
#main
if__name__=='__main__':
gongzhonghao=raw_input(u'輸入要爬取的公眾號')
ifnotgongzhonghao:
gongzhonghao='python6359'
weixin_spider(gongzhonghao).run()
#!/usr/bin/python
#coding:utf-8
[python]view plain
3.獲取公眾號地址
從獲取到的網頁內容中,得到公眾號主頁地址, 這一步驟有很多方法, beautifulsoup、webdriver,直接使用正則,pyquery等都可以
這里使用的是pyquery的方法來查找公眾號主頁入口地址
[python]view plain
4.獲取公眾號主頁的文章列表
首先需要載入公眾號主頁,這里用的是phantomjs+webdriver, 因為這個主頁的內容需要JS 渲染載入,採用之前的方法只能獲得靜態的網頁內容
[python]view plain
得到主頁內容之後,獲取文章列表,這個文章列表中有我們需要的內容
[python]view plain
5.解析每一個文章列表,獲取我們需要的信息
6.處理對應的內容
包括文章名字,地址,簡介,發表時間等
7.保存文章內容
以html的格式保存到本地
同時將上一步驟的內容保存成excel 的格式
8.保存json數據
這樣,每一步拆分完,爬取公眾號的文章就不是特別難了。
三、源碼
第一版源碼如下:
[python]view plain
第二版代碼:
對代碼進行了一些優化和整改,主要:
1.增加了excel存貯
2.對獲取文章內容規則進行修改
3.豐富了注釋
本程序已知缺陷: 如果公眾號的文章內容包括視視頻,可能會報錯。
[python]view plain
❽ python可以實現對微信朋友圈的抓取嗎
在 Hibernate 中,如果將屬性 id 定義為 Integer 類型,那麼 Hibernate 就可以根據其 值是否為 null 而判斷一個對象是否是臨時的,如果將 id 定義為了 int 類型,還需要在 hbm 映 射文件中設置其 unsaved-value 屬性為 0。
❾ 用python能爬到微信朋友圈動態嗎
這個一般是比較困難的
首先你需要相應的介面,另外還需要朋友圈相關的許可權等