python爬虫---requests库的用法

requests是python实现的简单易用的HTTP库,使用起来比urllib简洁很多

因为是第三方库,所以使用前需要cmd安装

pip install requests

安装完成后import一下,正常则说明可以开始使用了。

基本用法:

requests.get()用于请求目标网站,类型是一个HTTPresponse类型

import requests

response = requests.get(‘http://www.baidu.com‘)print(response.status_code)  # 打印状态码print(response.url)          # 打印请求urlprint(response.headers)      # 打印头信息print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印网页源码print(response.content) #以字节流形式打印

运行结果:

状态码:200

url:www.baidu.com

headers信息

各种请求方式:

import requests

requests.get(‘http://httpbin.org/get‘)
requests.post(‘http://httpbin.org/post‘)
requests.put(‘http://httpbin.org/put‘)
requests.delete(‘http://httpbin.org/delete‘)
requests.head(‘http://httpbin.org/get‘)
requests.options(‘http://httpbin.org/get‘)

基本的get请求

import requests

response = requests.get(‘http://httpbin.org/get‘)
print(response.text)

结果

带参数的GET请求:

第一种直接将参数放在url内

import requests

response = requests.get(http://httpbin.org/get?name=gemey&age=22)
print(response.text)

结果

另一种先将参数填写在dict中,发起请求时params参数指定为dict

import requests

data = {
    ‘name‘: ‘tom‘,
    ‘age‘: 20
}

response = requests.get(‘http://httpbin.org/get‘, params=data)
print(response.text)

结果同上

解析json

import requests

response = requests.get(‘http://httpbin.org/get‘)
print(response.text)
print(response.json())  #response.json()方法同json.loads(response.text)
print(type(response.json()))

结果

简单保存一个二进制文件

二进制内容为response.content

import requests

response = requests.get(‘http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg‘)
b = response.content
with open(‘F://fengjing.jpg‘,‘wb‘) as f:
    f.write(b)

为你的请求添加头信息

import requests
heads = {}heads[‘User-Agent‘] = ‘Mozilla/5.0 ‘ \                          ‘(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ‘ \                          ‘(KHTML, like Gecko) Version/5.1 Safari/534.50‘
 response = requests.get(‘http://www.baidu.com‘,headers=headers)

使用代理

同添加headers方法,代理参数也要是一个dict

这里使用requests库爬取了IP代理网站的IP与端口和类型

因为是免费的,使用的代理地址很快就失效了。

import requests
import re

def get_html(url):
    proxy = {
        ‘http‘: ‘120.25.253.234:812‘,
        ‘https‘ ‘163.125.222.244:8123‘
    }
    heads = {}
    heads[‘User-Agent‘] = ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0‘
    req = requests.get(url, headers=heads,proxies=proxy)
    html = req.text
    return html

def get_ipport(html):
    regex = r‘<td data-title="IP">(.+)</td>‘
    iplist = re.findall(regex, html)
    regex2 = ‘<td data-title="PORT">(.+)</td>‘
    portlist = re.findall(regex2, html)
    regex3 = r‘<td data-title="类型">(.+)</td>‘
    typelist = re.findall(regex3, html)
    sumray = []
    for i in iplist:
        for p in portlist:
            for t in typelist:
                pass
            pass
        a = t+‘,‘+i + ‘:‘ + p
        sumray.append(a)
    print(‘高匿代理‘)
    print(sumray)

if __name__ == ‘__main__‘:
    url = ‘http://www.kuaidaili.com/free/‘
    get_ipport(get_html(url))

结果:

基本POST请求:

import requests

data = {‘name‘:‘tom‘,‘age‘:‘22‘}

response = requests.post(‘http://httpbin.org/post‘, data=data)

获取cookie

#获取cookie
import requests

response = requests.get(‘http://www.baidu.com‘)
print(response.cookies)
print(type(response.cookies))
for k,v in response.cookies.items():
    print(k+‘:‘+v)

结果:

会话维持

import requests

session = requests.Session()
session.get(‘http://httpbin.org/cookies/set/number/12345‘)
response = session.get(‘http://httpbin.org/cookies‘)
print(response.text)

结果:

证书验证设置

import requests
from requests.packages import urllib3

urllib3.disable_warnings()  #从urllib3中消除警告
response = requests.get(‘https://www.12306.cn‘,verify=False)  #证书验证设为FALSE
print(response.status_code)

打印结果:200

超时异常捕获

import requests
from requests.exceptions import ReadTimeout

try:
    res = requests.get(‘http://httpbin.org‘, timeout=0.1)
    print(res.status_code)
except ReadTimeout:
    print(timeout)

异常处理

在你不确定会发生什么错误时,尽量使用try...except来捕获异常

所有的requests exception:

Exceptions

import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException

try:
    response = requests.get(‘http://www.baidu.com‘,timeout=0.5)
    print(response.status_code)
except ReadTimeout:
    print(‘timeout‘)
except HTTPError:
    print(‘httperror‘)
except RequestException:
    print(‘reqerror‘)
时间: 2024-08-19 00:45:42

python爬虫---requests库的用法的相关文章

Python 爬虫—— requests BeautifulSoup

本文记录下用来爬虫主要使用的两个库.第一个是requests,用这个库能很方便的下载网页,不用标准库里面各种urllib:第二个BeautifulSoup用来解析网页,不然自己用正则的话很烦. requests使用,1直接使用库内提供的get.post等函数,在比简单的情况下使用,2利用session,session能保存cookiees信息,方便的自定义request header,可以进行登陆操作. BeautifulSoup使用,先将requests得到的html生成BeautifulSo

爬虫requests库的方法与参数

爬虫requests库的方法与参数 import requests """ # 1. 方法 requests.get requests.post requests.put requests.delete ... requests.request(method='POST') """ # 2. 参数 """ 2.1 url 2.2 headers 2.3 cookies 2.4 params 2.5 data,传请求体

解决python爬虫requests.exceptions.SSLError: HTTPSConnectionPool(host=&#39;XXX&#39;, port=443)问题

爬虫时报错如下: requests.exceptions.SSLError: HTTPSConnectionPool(host='某某某网站', port=443): Max retries exceeded with url: /login/ (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify fail

python爬虫---urllib库的基本用法

urllib是python自带的请求库,各种功能相比较之下也是比较完备的,urllib库包含了一下四个模块: urllib.request   请求模块 urllib.error   异常处理模块 urllib.parse   url解析模块 urllib.robotparse    robots.txt解析模块 下面是一些urllib库的使用方法. 使用urllib.request import urllib.request response = urllib.request.urlopen(

爬虫——Requests库初识

1.Requests是什么 首先Requests是HTTP库,在爬虫中用于请求的相关功能. 而且requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库. 默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装. 2.Requests的使用 import requests response = requests.get('https://www.baidu.com') print(response.text) print(respo

[爬虫] requests库

requests库的7个常用方法 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(

python中requests库使用方法详解

一.什么是Requests Requests 是?ython语?编写,基于urllib,采?Apache2 Licensed开源协议的 HTTP 库.它? urllib 更加?便,可以节约我们?量的?作,完全满?HTTP测试需求. ?句话--Python实现的简单易?的HTTP库 二.安装Requests库 进入命令行win+R执行 命令:pip install requests 项目导入:import requests 三.各种请求方式 直接上代码,不明白可以查看我的urllib的基本使用方法

Python 爬虫 解析库的使用 --- XPath

一.使用XPath XPath ,全称XML Path Language,即XML路径语言,它是一门在XML文档中查找信息的语言.它最初是用来搜寻XML文档的,但是它同样适用于HTML文档的搜索. 所以在爬虫时,我们完全可以使用XPath来做相应的信息提取.本次随笔中,我们就介绍XPath的基本用法. 1.XPath概览 XPath的选择功能十分强大,它提供了非常简洁明了的路径选择表达式.另外,它还提供了超过100个内建函数,用于字符串.数值.时间的匹配以及节点.序列的处理等.几乎所有我们想要定

Python教程 | Requests的基本用法

下面我就给大家整理了Requests库的使用方法和细节. 什么是Requests Requests是Python语言编写,基于urllib3,采用Apache2 Licensed开源协议的HTTP库.它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求.是Python实现的简单易用的HTTP库. 安装也很简单: pip install requests Request的语法操作 1.实例引入 2.各种请求方式 请求 1.基本GET请求 2.带参数的GET请求这个我们前面有使