从零开始学Python-3(Request 入门的小案例)

本文是在Mooc上学习Python的笔记,原题如下

http://www.icourse163.org/course/BIT-1001870001

Robots协议

作用:
网站告知网络爬虫哪些页面可以抓取,哪些不行

形式:
在网站根目录下的robots.txt文件

例如

https://www.jd.com/robots.txt

结果如下

User-agent: * 
Disallow: /?* 
Disallow: /pop/*.html 
Disallow: /pinpai/*.html?* 
User-agent: EtaoSpider 
Disallow: / 
User-agent: HuihuiSpider 
Disallow: / 
User-agent: GwdangSpider 
Disallow: / 
User-agent: WochachaSpider 
Disallow: /

注释,*代表所有,/代表根目录

User‐agent: *

Disallow: /

五个Requests库网络爬取的小例子

例子一 京东商品爬取

import requests
url = 'http://www.icourse163.org/course/BIT-1001870001'
try:
    r = requests.get(url)
    r.raise_for_status()   #Raises stored HTTPError, if one occurred.
    #如果发生了HTTP错误,就把这个错误存储起来
    r.encoding = r.apparent_encoding
    print(r.text[:1000])
except:
    print('爬取失败')

例子二 爬取不允许爬虫访问的亚马逊

import  requests
url = 'https://www.amazon.cn/dp/B01MSKJZ5J/ref=lp_1753445071_1_1?s=shoes&ie=UTF8&qid=1587470105&sr=1-1'
try:
    kv = {'user-agent':'Mozilla/5.0'}       #一个字典,用来模拟头部信息的
    r = requests.get(url,headers=kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[1000:2000])
except:
    print('爬取失败')

例子三 百度搜索全代码

import  requests
keyword = 'Python'
try:
    kv = {'wd':keyword}     #字典或字节序列,作为参数增加到url中
    r = requests.get('http://www.baidu.com/s',params=kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print('爬取失败')

例子四 网络图片的爬取和存储

import requests
import os
url = 'http://img0.dili360.com/pic/2020/04/21/5e9ea4243bfc74p24083429.jpg@!rw9'
root = 'F://pics//'
path = root + url.split('/')[-1]
try:
    if not os.path.exists(root):        #如果不存在这个路径的话
        os.mkdir(root)                  #创建这个路径
        print('存在这个路径')
    if not os.path.exists(path):        #如果这个文件不存在
        r = requests.get(url)
        with open(path,'wb') as f:
            f.write(r.content)          #把content写入content里面
            f.close()
            print('文件保存成功')
    else:
        print('文件已存在')

except:

    print('爬取失败')

例子五 IP地址归属地的自动查询

import requests
url = 'http://m.ip138.com/ip.asp?ip='   #获取ip的url
try:
    r = requests.get(url+'202.204.80.112')
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[-500:])
except:
    print('爬取失败')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值