python爬蟲三個小案例(入門)

    爬蟲很久沒有寫了,這次用python來寫一波入門教程。

有道翻譯api接口翻譯英文單詞

這個可以在網上找教程,我是參考如下大神的。
傳送門
這個說是爬蟲,但是我個人更覺得像api接口調用。這裏面具體就是我輸入一個英文單詞,然後將單詞拼接到api的url上面,之後返回翻譯信息。

#!/usr/bin/env python
# encoding: utf-8

import json

from urllib.parse import urlencode
from urllib.request import urlopen

def fetch(query_str=''):
    #去除查詢字符串頭尾的引號,雙引號,空格
    query_str = query_str.strip("'").strip('"').strip()
    #設置查詢默認值
    if not query_str:
        query_str = 'python'

    #查詢字符串
    query = {
        'q' : query_str
    }
    #api接口
    url = 'http://fanyi.youdao.com/openapi.do?keyfrom=11pegasus11&key=273646050&type=data&doctype=json&version=1.1&' + urlencode(query)

    #請求接口,並獲取數據
    response = urlopen(url,timeout=3)

    #讀取所有返回數據,並按utf8解碼
    html = response.read().decode('utf-8')

    return html

def parse(html):

    d = json.loads(html)
    try:
        if d.get('errorCode') == 0:
            explains = d.get('basic').get('explains')
            for i in explains:
                print(i)
        else:
            print('無法翻譯')
    except:
        print('翻譯出錯,請輸入合法單詞')

def main():
    while True:
        s = input('輸入所要翻譯英文單詞:')
        if s == 'exit':
            break
        else:
            parse(fetch(s))


if __name__ == '__main__':
    main()

效果圖

北京天氣任意時間段查詢

    這個天氣網站是http://tianqi.2345.com。在這個網站上面其實很容易找到規律。
效果圖
這個網站在歷史天氣搜索界面上,按F5,然後看network裏面的內容。很容易找到返回數據的鏈接其實就是請求了一個js腳本。而且url很有規律,讓我們爬起來更加順手。
http://tianqi.2345.com/t/wea_history/js/201806/54511_201806.js
這種url很明顯就是時間加城市編碼來請求的。實現代碼如下

#!/usr/bin/env python
# encoding: utf-8

import re
import json
from urllib.request import urlopen

#時間區間輸入
#[開始時間,結束時間)
def month2month(year1,month1,year2,month2):
    #日期列表
    months = []
    year = year1
    month = month1
    month2 = month2 +1
    if month2==13:
        year2 = year2 + 1
        month2 = 1

    while year != year2 or month != month2:

        mstr = str(year).zfill(2)+str(month).zfill(2)
        months.append(mstr)
        month = month + 1
        if(month == 13):
            year = year + 1
            month = 1

    return months

def getWeather(month):
    # 這是url後面拼接的字符串'201805/54511_201805.js'
    # 54511是北京編號,還有就是時間標識
    city = '54511'
    url = f'http://tianqi.2345.com/t/wea_history/js/{month}/{city}_{month}.js'

    response = urlopen(url,timeout=5)

    #print(response.read())

    html = response.read().decode('gbk')
    html.encode('utf-8')

    return  html

def parse(html):
    mjson = html.strip('var weather_str=').strip(';').replace("'","\"")
    rejson = re.sub(r'(\w+):',r'"\1":',mjson)
    #print(rejson)
    d = json.loads(rejson)
    return d

def main():
    months = month2month(2018,6,2018,6)
    print(months)
    for month in months:
        html = getWeather(month)
        weather = parse(html)
        print(weather)

    print(f"city:{weather['city']}")
    for item in weather['tqInfo']:
        try:
            print(f"時間:{item['ymd']} 最高溫:{item['bWendu']} 最低溫:{item['yWendu']} 天氣:{item['tianqi']} 風向風力:{item['fengxiang']},{item['fengli']} 空氣質量:{item['aqi']},{item['aqiInfo']}")
        except:
            continue

if __name__ == '__main__':
    main()

效果圖

京東電腦3000-5000信息爬取

    這裏面要規定的價格爬取區間其實非常容易實現,只要用jd自己的篩選功能就能實現,然後信息頁面就出來了。這裏面京東的商品信息實在是非常複雜,看了接口發現沒什麼明顯規律,所以這裏面直接用正則表達式來爬頁面信息算了。
    首先請求頁面代碼,然後寫正則表達式嗎,最後數據組裝就ok了。
具體實現如下:

#!/usr/bin/env python
# encoding: utf-8

import os
import re
import json

from urllib.request import urlopen

url = 'https://list.jd.com/list.html?cat=670,671,672&ev=exprice_M3000L5000&page=1&sort=sort_totalsales15_desc&trans=1&JL=6_0_0#J_main'

if __name__ == '__main__':
    html = urlopen(url,timeout=5)
    #f = open('D:\python\jd.html','w+',encoding='utf-8')
    #f.write(html.read().decode('utf-8'))
    #f.close()

    #獲取商品url和名稱
    pat = r'<a\s+?target="_blank"\s+?title=""\s+?href="([^\"]+)">[\s]*?<em>([^<]+?)</em>'
    string = html.read().decode('utf-8')
    it = re.finditer(pattern=pat,string=string)
    print('匹配')
    goodList = []
    for match in it:
        #print(match.group(0))
        #print(match.group(1))
        #print(match.group(2))
        goodList.append({'url':match.group(1),'title':match.group(2).strip()})

    pat = '<img width="220" height="220" data-img="1" (?:src|data-lazy-img)="([^\"]+?)"[^>]*?>'
    it = re.finditer(pattern=pat,string=string)
    imgs = []
    for match in it:
        #print(match.group(0))
        #print(match.group(1))
        imgs.append(match.group(1))

    size = len(goodList)
    print(size)
    print(len(imgs))
    pass
    for key in range(0,size):
        try:
            goodList[key]['img'] = imgs[key]
            print(goodList[key])
        except:
            print('出錯了')
    print(goodList)

效果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章