Python爬虫-常用的请求方式

爬虫的请求方式常用的有urllib和requests,前者是自带模块,后者需要我们自己进行安装。

安装requests模块

pip3 install requests

urllib

注意:在 python2 中,urllib 被分为urllib,urllib2等,在python3中我们直接使用urllib

urlopen方法的使用# 导入urllib.request 库
import urllib.request

向指定的url发送请求,并返回服务器响应的类文件对象

response = urllib.request.urlopen("http://www.baidu.com")
print(type(response))

类文件对象支持文件对象的操作方法,

如read()方法读取文件全部内容,返回
字符串(注意我们在使用read()获取响应
结果的时候,执行一次后,下次在执行就没有数据了)
html = response.read()

打印响应结果(betys类型)

print (html)

打印状态码

print (response.status)

获取响应头

print (response.getheaders())

获取响应头信息

print (response.getheader('Server'))

获取响应结果原因

print (response.reason)

  • url:设置目标url
  • data:如果设置该参数,则请求默认为post请求
  • timeout:用于设置超时时间,单位为秒
  • context:必须是一个ssl.SSLContext类型,用来指定SSL设置,忽略未认证的CA证书

requests 的是使用

虽然Python的标准库中 urllib 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 "HTTP for Humans",说明使用更简洁方便。

requests 的底层实现其实就是 urllib

基本GET请求

  1. 最基本的GET请求可以直接用get方法response = requests.get("http://www.baidu.com/")

也可以这么写

response = requests.request(
"get",
"http://www.baidu.com/"
)

response的常用方法:

    * response.text 返回解码后的字符串
    * respones.content 以字节形式(二进制)返回。
    * response.status_code  响应状态码
    * response.request.headers  请求的请求头
    * response.headers  响应头
    * response.encoding = 'utf-8' 可以设置编码类型
    * response.encoding 获取当前的编码
    * response.json() 内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
2. 添加 headers 和 params查询参数如果想添加 headers,可以传入headers参数来增加请求头中的headers信息。如果要将参数放在url中传递,可以利用 params 参数。
import requests

kw = {'wd':'长城'}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}

# params 接收一个字典或者字符串的查询参数,
# 字典类型自动转换为url编码,不需要urlencode()
response = requests.get(
    "http://www.baidu.com/s?",
    params = kw, 
    headers = headers
)

# 查看响应内容,response.text 返回的是Unicode格式的数据
print (response.text)

当收到一个响应时,Requests 会猜测响应的编码方式,用于在你调用response.text 方法时对响应进行解码。Requests 首先在 HTTP 头部检测是否存在指定的编码方式,如果不存在,则会使用chardet.detect来尝试猜测编码方式(存在误差) 故更推荐使用response.content.deocde()
基本POST请求(data参数)1. 最基本post方法response = requests.post(url=url, data = data)

url:post请求的目标url
data:post请求的表单数据
  1. 传入data数据
    post需要传入参数的时候,我们定义一个变量form_data,将浏览器控制台我们拿到的表单数据复制进来。如下:
form_data={
        'sex': 'f','key':'','stc': '1:11,2:20.28,23:1',
        'sn': 'default','sv': '1','p': str(page),
        'f': 'search','listStyle': 'bigPhoto',
        'pri_uid': '0','jsversion': 'v5',
    }

请求头

header = {
    'Referer': 'http://search.jiayuan.com/v2/index.php?sex=f&stc=1:11,2:20.28,23:1&f=search',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
}

请求的url地址

url = 'http://search.jiayuan.com/v2/search_v2.php'

发起请求,携带url,请求头,表单数据,得到响应结果response

response = requests.post(url,headers=header,data=form_data)

print(response.text)

注:如果是json文件可以直接显示

print (response.json())

你可能感兴趣的:(Python爬虫-常用的请求方式)