python爬蟲2

Liam_Fang_發表於2019-01-07

1.這裡是記錄下怎麼是實現用爬蟲爬取天氣資訊再將資訊以簡訊的方式傳送給指定的人。

首先爬取天氣資訊,這裡爬取深圳的天氣,這裡如果對爬蟲不是很瞭解可以看下https://www.cnblogs.com/zhaof/p/6930955.html

import requests
from lxml import etree
from bs4 import BeautifulSoup
import datetime
import re
def get_info():
    headers = {"User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36"
    }
    html = requests.get("https://www.tianqi.com/shenzhen/life.html",headers=headers)
    html.encoding="utf-8"
    soup=BeautifulSoup(html.text,'lxml')
    title=soup.find('div',{'class':"tit01"})
    h1=title.find('h1')
    print(h1.get_text())
    title=h1.get_text()
    print(soup.select('.lifeindex li')[0].select('b')[0].get_text())
    daisan = soup.select('.lifeindex li')[0].select('b')[0].get_text()
    daisan1 = soup.select('.lifeindex li')[0].select('p')[0].get_text()
    print(daisan1)
    zhiwaixian = soup.select('.lifeindex li')[2].select('b')[0].get_text()
    print(zhiwaixian)
    zhiwaixian1 = soup.select('.lifeindex li')[2].select('p')[0].get_text()
    print(zhiwaixian1)
    chuanyi = soup.select('.lifeindex li')[5].select('b')[0].get_text()
    print(chuanyi)
    chuanyi1 = soup.select('.lifeindex li')[5].select('p')[0].get_text()
    print(chuanyi1)
    travel = soup.select('.lifeindex li')[6].select('b')[0].get_text()
    print(travel)
    travel1 =soup.select('.lifeindex li')[6].select('p')[0].get_text()
    print(travel1)
    liangsai = soup.select('.lifeindex li')[7].select('b')[0].get_text()
    print(liangsai)
    liangsai1 =soup.select('.lifeindex li')[7].select('p')[0].get_text()
    print(liangsai1)
    #獲取當前時間
    today=datetime.datetime.now().strftime('%Y/%m/%d')
    resmes = title+":"+today+ '\n' + daisan +":"+daisan1+'\n'+zhiwaixian+':'+zhiwaixian1+'\n'+chuanyi+':'+chuanyi1+'\n'+travel+':'+travel1+'\n'+liangsai+":"+liangsai1+'\n'
    print(resmes)
    return resmes
text = get_info()
print(text)

上面獲得的結果是

 

 2安裝twilio

pip install twilio

安裝好,去該網站註冊獲得一個電話號碼,這樣傳送簡訊就是通過這個電話號碼傳送的,這裡要科學上網,具體要求看這位博主的https://blog.csdn.net/fengfengdiandia/article/details/52719214

傳送簡訊的程式碼

from twilio.rest import Client
from info import get_info
print(get_info())
text=get_info()
ACCOUNT_SID="twilio的賬戶名"
AUTH_TOKEN="twilio密碼"
client = Client(ACCOUNT_SID,AUTH_TOKEN)
mes1 = client.messages.create(
    from_='在twilio獲得的電話,這裡傳送簡訊就是通過這個傳送的',
    body=text,
    to='目標電話號碼,需要在twilio上驗證'
)
print(mes1)

最終目標手機獲得相應的資訊結果就說明成功了。

參考bilibili

http://www.bilibili.com/video/av39346491?share_medium=android&share_source=copy_link&bbid=XY4FB074F357BC18FFBA4E2114AB87AACAC21&ts=1546830382973

相關文章