官方接口文档:
抓取天气的例子:
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"
# 给特定好友发送
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)
#给所有微信好友发送
# friends = itchat.get_friends()
for f in nicks:
# 给所有微信好友发送
# 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)
待扩展