Unit2 Requests库的常用方法

1. Requests库中常用的七种方法

  • requests.request()     %构造一个请求,支持以下各方法的基本方法
  • requests.get()            %获取HTML网页的主要方法,对应于HTTP的GET
  • requests.head()         %获取HTML网页头信息的方法,对应于HTTP的HEAD
  • requests.post()           %向HTML网页提交POST请求的方法,对应于HTTP的POST
  • requests.put()             %向HTML网页提交PUT请求的方法,对应于HTTP的PUT
  • requests.patch()         %向HTML网页提交局部修改请求,对应于HTTP的PATCH
  • requests.delete()         %向HTML网页提交删除请求,对应于HTTP的DELETE

2. Requests库的get()方法

由于安全性等原因,我们很少使用patch()、put()、post()、delete()对url进行访问,所以使用最多的是get()。

r = requests.get(url)      %get构造一个向服务器请求资源的Request对象,返回一个包含服务器资源的Response对象。

 需要主要的是,网络连接有风险,异常处理很重要。所以我们需要使用try...except结构来访问url。

3. 实例解析

下面给出五个实例:

1.京东商品页面的爬取

import requests
url = "https://item.jd.com/2967929.html"
try: r = requests.get(url) r .raise_for_status() r.encoding = r.apparent_encoding print(r.text[:1000])except: print("爬取失败")

2.亚马逊商品页面的爬取 

如果使用上述代码返回的状态码不是200,则需要对该代码进行一些修改,具体如下:

import requests
url = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"
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("爬取失败")   

通过headers字段让我们的代码模拟浏览器向该网址提交访问请求,这对于许多对自己数据保护较好的网站适用。

3.百度/360搜索关键词提交

用程序向百度/360提交一个关键词,并且获取搜索结果。

百度的关键词接口:

http://www.baidu.com/s?wd=keyword

360搜索的关键词接口:

http://www.so.com/s?q=keyword

只要替换keyword就可以向搜索引擎提交关键字。

import requests
keyword = "Python"
try:
     kv = {'wd':keyword}
     r = requests.get("http://www.baidu.com/s",params = kv)
     print(r.request.url)
     r.raise_for_status()
     print(len(r.text))
except:
     print("爬取失败")

4.网络图片的爬取和存储

网络上图片链接的格式:htttp://www.example.com/picture.jpg

import requests
import os
url = "https://www.baidu.com/img/bd_logo1.png"
root = "F://pics//"
path = root + url.split('/')[-1]
try:
     if not os.path.exists(root):
          os.mkdir(root)
     if not os.path.exists(path):
          r = requests.get(url)
          with open(path, 'wb') as f:
               f.write(r.content)
               f.close()
               print("文件保存成功")
     else:
          print("文件已存在")
except:
     print("爬取失败")

5.IP地址归属地的自动查询

import requests
url = "http://m.ip138.com/ip.asp?ip="
try:
    r = requests.get(url+'210.45.192.102')
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[-500:])
except:
     print("爬取失败")

 

posted on 2017-12-14 10:26  Firmiana1220  阅读(192)  评论(0)    收藏  举报