python 是一門面向?qū)ο蟮哪_本語言歉甚,其語法類似于英語語法的特性受很多人喜歡,簡潔的編碼風(fēng)格不像java需要多行的代碼申明益缠。(片面之談)
清明節(jié)假期的漫長時(shí)間脑奠,窩在寢室中,看著Python的教學(xué)視頻幅慌,枯燥乏味宋欺,故而牛刀小試網(wǎng)絡(luò)爬蟲,有記得過年時(shí)期在知乎上有看到基于python的微信自動回復(fù)拜年問好胰伍,做了個(gè)自動回復(fù)糗事百科上小笑話的小腳本齿诞。
python 的類屬性是定義在init方法里的,在類里調(diào)用 self.屬性
類方法 里的第一個(gè)參數(shù) 為 對象自身骂租。
對于函數(shù)里的變量祷杈,用global 修飾可以使其擴(kuò)展作用域?yàn)槿肿兞俊?/p>
# *-* coding:UTF-8 *-*
import itchat, time, re
from itchat.content import *
import urllib,re
from urllib.request import Request,urlopen,URLError
class WechatContent:
def __init__(self):
self.stories=[] #存放段子
self.pageIndex = 1
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
self.headers={ 'User-Agent' : self.user_agent} #初始化headers
self.enable=True #程序是否運(yùn)行的變量
#獲取網(wǎng)頁內(nèi)容
def getWebPage(self):
url="http://www.qiushibaike.com/hot.page"+str(self.pageIndex)
request=Request(url,headers=self.headers)
try:
response=urlopen(request)
#print(response.read())
return response.read().decode('utf-8') #將頁面轉(zhuǎn)為utf-8
except URLError as e:
if hasattr(e,'reason'):
print(u"連接錯(cuò)誤",e.reason)
return None
#獲取段子
def getContent(self):
content=self.getWebPage()
if not content:
return 0;
else:
pattern=re.compile('<div class="content">\s*<span>\s*(\S*?)\s*</span>\s*</div>',re.S)
items=re.findall(pattern,content)
for item in items:
item.replace("\s*","")
self.stories.append(item)
#發(fā)送段子
def postContent(self):
story=self.stories.pop()
#print (story)
return story
def start(self):
if not self.stories:
self.pageIndex+=1
self.getContent()
wc=WechatContent()
wc.start()
#print(wc.postContent())
priortext='hello world'
@itchat.msg_register([TEXT])
def text_reply(msg):
if not wc.postContent():
wc.start()
text=wc.postContent()
friend=itchat.search_friends(userName=msg['FromUserName'])
print(friend['RemarkName'])
print(msg['Text'])
print("回復(fù):\t",text)
itchat.send(text ,msg['FromUserName'])
@itchat.msg_register([PICTURE, RECORDING, VIDEO, SHARING])
def other_reply(msg):
itchat.send(priortext, msg['FromUserName'])
itchat.auto_login(enableCmdQR=True,hotReload=True)
itchat.run()
哈哈,自動回復(fù)中我后來加了渗饮,收到消息中有“什么”字樣時(shí)但汞,回復(fù)“我給找的段子搞笑吧,哈哈”互站,然后朋友以為我給他找了好多段子私蕾。