美文网首页
网络爬虫入门 (一) Requests的使用

网络爬虫入门 (一) Requests的使用

作者: 闻榴莲的猫 | 来源:发表于2018-07-16 19:45 被阅读0次

一、简介

Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开原协议的HTTP库。相对urllib使用起来更加方便,可以节约大量工作。

安装方法:

  • conda install requests或者pip install requests
  • conda list或者pip list查看环境内是否已安装

使用help(requests)方法可以查看requests的帮助文档

二、请求方式

1、 get请求

import requests
res = requests.get("http://www.baidu.com")#get请求
print(res)#响应
print(res.status_code)#返回请求的状态码,成功时为200
print(res.text)
print(res.encoding)#字符编码
print(res.cookies)
print(res.headers)#响应头
#将请求到的结果保存到当前目录下
# with open("./test.html", "w", encoding="utf-8") as file:
#     file.write(res.text)

2、post请求

import requests
params = {"key1": "value1", "key2": "value2"}
try:
    response = requests.post("http://httpbin.org", data=params)
    print(response.status_code)
    print(response.text)
except requests.exceptions.ConnectionError as e:
    print("服务器连接失败")

三、常用API

1、设置请求头

在实际爬取网站的过程中,经常会碰到服务器的反爬策略,其中之一的解决方法就是模拟浏览器的请求头,
可以在请求

import requests
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36"}
proxies = {
    "http":"122.72.32.73:80",
    "https":"58.67.159.50:80"
}
#进行get请求的同时设置请求头和代理IP
response = requests.get("http://www.tmall.com", headers=headers, proxies=proxies)
print(response.status_code)
print(response.text)

总体来说使用难度较低,可以配合官方文档一起学习
http://docs.python-requests.org/en/latest/user/quickstart.html

相关文章

网友评论

      本文标题:网络爬虫入门 (一) Requests的使用

      本文链接:https://www.haomeiwen.com/subject/ogxbpftx.html