99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀如何用 Python 爬取天氣預(yù)報
如何用 Python 爬取天氣預(yù)報
2018-01-23
收藏

如何用 Python 爬取天氣預(yù)報

大家好,我是Victor 278,由于本人是做前端的,Python學(xué)來作知識擴充的,看到非常多的小伙伴高呼著想從0開始學(xué)爬蟲,這里開始寫定向爬蟲從0開始,獻給想學(xué)爬蟲的零基礎(chǔ)新人們,歡迎各位大佬們的指點。

本文適用人群
1、零基礎(chǔ)的新人;
2、Python剛剛懂基礎(chǔ)語法的新人;
輸入標(biāo)題學(xué)習(xí)定向爬蟲前需要的基礎(chǔ)
1、Python語法基礎(chǔ);
2、請閱讀或者收藏以下幾個網(wǎng)站:
1)Requests庫
http://cn.python-requests.org/zh_CN/latest/
2)BeautifulSoup4庫
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
沒有Python基礎(chǔ)的新人,我建議可以學(xué)習(xí)以下資料:
1、官方最新的英文文檔(https://docs.python.org/3/)
2、python 3.60版本中文文檔(http://www.pythondoc.com/pythontutorial3/index.html)
3、廖雪峰Python教程(https://www.liaoxuefeng.com/)
備注:書籍也有很多選擇,但是其實入門教程講來講去都是那些東西,不做細(xì)究,你隨意挑一本完完整整的學(xué)習(xí)好比你浪費時間選擇教材要強多了。
正文開始
我假設(shè)你已經(jīng)符合上述的標(biāo)準(zhǔn),現(xiàn)在我們就來開始第一個爬蟲的網(wǎng)站,我們首先挑選一個下手;
附上URL:中國天氣網(wǎng)(http://www.weather.com.cn/weather1d/101280101.shtml#dingzhi_first)
第一步:
請確保你已經(jīng)安裝了Requests和Beautifulsoup4的庫,否則你可以打開CMD(命令提示符)然后輸入
pip3 install requests
pip3 install Beautifulsoup4
pip3 install lxml
安裝完畢后接著打開你的編輯器,這里對編輯器不做糾結(jié),用的順手就好。
首先我們做爬蟲,拿到手第一個步驟都是要先獲取到網(wǎng)站的當(dāng)前頁的所有內(nèi)容,即HTML標(biāo)簽。所以我們先要寫一個獲取到網(wǎng)頁HTML標(biāo)簽的方法。
整個爬蟲的的代碼搭建我都采用的是將不同的功能做成不同的函數(shù),在最后需要調(diào)用的時候進行傳參調(diào)用就好了。
那么問題來了,為什么要這么做呢?
寫代碼作為萌新要思考幾件事:
1、這個代碼的復(fù)用性;
2、這個代碼的語義化以及功能解耦;
3、是否美觀簡潔,讓別人看你的代碼能很清楚的理解你的邏輯;
代碼展示:
'''
抓取每天的天氣數(shù)據(jù)
python 3.6.2
url:http://www.weather.com.cn/weather1d/101280101.shtml#dingzhi_first
'''
import requests
import bs4

def get_html(url):
    '''
    封裝請求
    '''
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
        'ContentType':
        'text/html; charset=utf-8',
        'Accept-Encoding':
        'gzip, deflate, sdch',
        'Accept-Language':
        'zh-CN,zh;q=0.8',
        'Connection':
        'keep-alive',
    }
    try:
        htmlcontet = requests.get(url, headers=headers, timeout=30)
        htmlcontet.raise_for_status()
        htmlcontet.encoding = 'utf-8'
        return htmlcontet.text
    except:
        return " 請求失敗 "
上述代碼幾個地方我特別說明一下:
'''
抓取每天的天氣數(shù)據(jù)
python 3.6.2
url:http://www.weather.com.cn/weather1d/101280101.shtml#dingzhi_first
'''
import requests
import bs4
養(yǎng)成好習(xí)慣代碼一開始的注釋表明這是一個什么功能的Python文件,使用的版本是什么,URL地址是什么,幫助你下次打開的時候能快速理解這個文件的用途。
由于Requests和Beautifulsoup4是第三方的庫,所以在下面要用import來進行引入
然后是
def get_html(url):
    '''
    封裝請求
    '''
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
        'ContentType':
        'text/html; charset=utf-8',
        'Accept-Encoding':
        'gzip, deflate, sdch',
        'Accept-Language':
        'zh-CN,zh;q=0.8',
        'Connection':
        'keep-alive',
    }
    try:
        htmlcontet = requests.get(url, headers=headers, timeout=30)
        htmlcontet.raise_for_status()
        htmlcontet.encoding = 'utf-8'
        return htmlcontet.text
    except:
        return " 請求失敗 "
其中
def get_html(url):
構(gòu)造一個名為get_html的函數(shù),并傳入你要請求的URL地址進去,會返回一個請求后的結(jié)果,
構(gòu)造好后,調(diào)用的時候直接
url = '包裹你的url'
get_html(url)
然后同樣備注好你的這個函數(shù)的功能是做什么的,headers里面包裹了一些偽裝成瀏覽器訪問的一些頭部文件可以直接你復(fù)制過去使用。
這里要說一下為什么要做基礎(chǔ)的偽裝成瀏覽器,由于有了爬蟲,自然就有反爬蟲。有些網(wǎng)站為了惡意避免爬蟲肆意爬取或者進行攻擊等等情況,會做大量的反爬蟲。偽裝瀏覽器訪問是反爬蟲的一小步。
好了我們繼續(xù),
htmlcontet = requests.get(url, headers=headers, timeout=30)
htmlcontet.raise_for_status()
htmlcontet.encoding = 'utf-8'
return htmlcontet.text
第一條如果我們看了Requests之后就知道這是一個解析你傳入的url,并包含了請求頭,響應(yīng)延時
第二條,如果當(dāng)前頁面響應(yīng)的情況會返回一個json數(shù)據(jù)包,我們通過這個語法來確認(rèn)是否為我們要的成功響應(yīng)的結(jié)果
第三條,解析格式,由于該網(wǎng)站我們可以看到已知字符編碼格式為utf-8所以在這里我就寫死了是utf-8
最后都沒問題后,返回一個頁面文件出來
第二步:
拿到一個頁面文件后,我們就需要觀察一下該網(wǎng)頁的HTML結(jié)構(gòu)
這里介紹一下如何觀察一個網(wǎng)頁的結(jié)構(gòu),打開F12或者,找個空白的位置右鍵——>檢查
我們大概會看到這樣的一個情況:

沒錯你看到那些<body><div>這些就是HTML語言,我們爬蟲就是要從這些標(biāo)記里面抓取出我們所需要的內(nèi)容。
我們現(xiàn)在要抓取這個1日夜間和2日白天的天氣數(shù)據(jù)出來:
我們首先先從網(wǎng)頁結(jié)構(gòu)中找出他們的被包裹的邏輯

很清楚的能看到他們的HTML嵌套的邏輯是這樣的:
<div class="con today clearfix">
|
|_____<div class="left fl">
   |
   |_____<div class="today clearfix" id="today">
      |
      |______<div class="t">
         |
         |_____<ul class="clearfix">
            |
            |_____<li>
            |
            |_____<li>

我們要的內(nèi)容都包裹在li里面,然后這里我們就要用BeautifulSoup里面的find方法來進行提取查詢
我們繼續(xù)構(gòu)建一個抓取網(wǎng)頁內(nèi)容的函數(shù),由于我們最終要的數(shù)據(jù)有兩條,所有我先聲明一個weather_list的數(shù)組來等會保存我要的結(jié)果。
代碼如下:
def get_content(url):
    '''
    抓取頁面天氣數(shù)據(jù)
    '''
    weather_list = []
    html = get_html(url)
    soup = bs4.BeautifulSoup(html, 'lxml')
    content_ul = soup.find('div', class_='t').find_all('li')
    for content in content_ul:
        try:
            weather = {}
            weather['day'] = content.find('h1').text
            weather['temperature'] = content.find(
                'p', class_='tem').span.text + content.find(
                    'p', class_='tem').em.text
            weather_list.append(weather)
        except:
            print('查詢不到')
    print (weather_list)
同樣的話不說第二遍,我們要寫好注釋。在聲明完數(shù)組后,我們就可調(diào)用剛才封裝好的請求函數(shù)來請求我們要的URL并返回一個頁面文件,接下來就是用Beautifulsoup4里面的語法,用lxml來解析我們的網(wǎng)頁文件。
你們可以用

soup = bs4.BeautifulSoup(html, 'lxml')
print (soup)
就可以看到整個HTML結(jié)構(gòu)出現(xiàn)在你眼前,接下來我就們就根據(jù)上面整理出來的標(biāo)簽結(jié)構(gòu)來找到我們要的信息
content_ul = soup.find('div', class_='t').find_all('li')
具體方法,要熟讀文檔,我們找到所有的li后會返回一個這樣的結(jié)構(gòu)

這是一個數(shù)組的格式,然后我們遍歷它,構(gòu)造一個字典,我們對于的操作字典建立'day','temperature'鍵值對

   for content in content_ul:
       try:
            weather = {}
            weather['day'] = content.find('h1').text
            weather['temperature'] = content.find(
                'p', class_='tem').span.text + content.find(
                    'p', class_='tem').em.text
            weather_list.append(weather)
        except:
            print('查詢不到')
    print(weather_list)

最后輸出

附上完整代碼:

'''
抓取每天的天氣數(shù)據(jù)
python 3.6.2
url:http://www.weather.com.cn/weather1d/101190401.shtml
'''
import json
import requests
import bs4

def get_html(url):
    '''
    封裝請求
    '''
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
        'ContentType':
        'text/html; charset=utf-8',
        'Accept-Encoding':
        'gzip, deflate, sdch',
        'Accept-Language':
        'zh-CN,zh;q=0.8',
        'Connection':
        'keep-alive',
    }
    try:
        htmlcontet = requests.get(url, headers=headers, timeout=30)
        htmlcontet.raise_for_status()
        htmlcontet.encoding = 'utf-8'
        return htmlcontet.text
    except:
        return " 請求失敗 "

def get_content(url):
    '''
    抓取頁面天氣數(shù)據(jù)
    '''
    weather_list = []
    html = get_html(url)
    soup = bs4.BeautifulSoup(html, 'lxml')
    content_ul = soup.find('div', class_='t').find('ul', class_='clearfix').find_all('li')
    for content in content_ul:
        try:
            weather = {}
            weather['day'] = content.find('h1').text
            weather['temperature'] = content.find(
                'p', class_='tem').span.text + content.find(
                    'p', class_='tem').em.text
            weather_list.append(weather)
        except:
            print('查詢不到')
    print(weather_list)

if __name__ == '__main__':
    url = 'http://www.weather.com.cn/weather1d/101190401.shtml'
    get_content(url)

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }