官方接口文檔:
抓取天氣的例子:
import sys
import requests as req
from lxml import etree
import itchat
# 轉碼
reload(sys)
sys.setdefaultencoding( "utf-8" )
# 定義url
shanghai_url = "http://www.nmc.cn/publish/forecast/ASH/shang-hai.html"
# 給特定好友發(fā)送
nicks = [
? ? 'xxx',
]
names = [
? ? 'xxx',
]
remarks = [
? ? 'xxx'
]
def geturlinfobyxpath(url):
? ? '''獲取URL頁面信息'''
? ? kv = {'user-agent': 'Mozilla/5.0'}
? ? r = req.get(url, headers=kv)
? ? r.raise_for_status()
? ? r.encoding = r.apparent_encoding
? ? tree = etree.HTML(r.text)
? ? nodes = tree.xpath('//div[@class="day"]/div/text()')
? ? city = tree.xpath('//title/text()')[0]
? ? updatetime = tree.xpath('//div[@class="btitle"]/span/text()')[0]
? ? newnode = ''.join(nodes).replace(' ', '').replace('\n\n', '\n').replace('\n\n', '\n')
? ? newnode = newnode[1:len(newnode)-1]
? ? infos = newnode.split(u'\n')
? ? for i in range(len(infos)):
? ? info = infos[i]
? ? if info.endswith(u'\u5929') or (u'\u6708' in info):
? ? infos[i] = u'\n' + info
? ? newnode = '\n'.join(infos)
? ? sms = '\n\n<xxx>'
? ? sendsms = '%s%s\n%s%s' % (city, updatetime, newnode, sms)
? ? print sendsms
? ? itchat.auto_login(hotReload=True)
? ? #給所有微信好友發(fā)送
? ? # friends = itchat.get_friends()
? ? for f in nicks:
? ? # 給所有微信好友發(fā)送
? ? # username = f.UserName
? ? user_name = itchat.search_friends(nickName=f)[0]['UserName']
? ? itchat.send_msg(sendsms, toUserName=user_name)
? ? #print(sendsms)
? ? for f in names:
? ? itchat.send_msg(sendsms, toUserName=f)
? ? for remark in remarks:
? ? user_name = itchat.search_friends(remarkName=remark)[0]['UserName']
? ? itchat.send_msg(sendsms, toUserName=user_name)
if __name__ == '__main__':
? ? geturlinfobyxpath(shanghai_url)
待擴展