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)

效果图

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值