爬虫必知的request模块

news/2024/7/19 8:42:29 标签: 爬虫, json, python

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

# 导入 Request模块
# 若本机无自带Request模块,可自行下载或者使用pip进行安装
# python版本Python3
import requests
import json

#######################Get请求#######################

# 发送无参数的get请求
baiDu_response = requests.get('http://www.baidu.com')

# 发送无参数的get请求 设置超时时间 timeout 单位秒
baiDu_response = requests.get('http://www.baidu.com', timeout=1)

# 查看发送请求的url地址
print('无参数的get请求地址为: ' + baiDu_response.url)

# 查看当前返回状态码
# 若状态码为200 等同于 baiDu_response.status_code == requests.codes.ok 返回为True
print('返回的状态码为: '+str(baiDu_response.status_code))

# 查看当前返回内容编码
print('返回内容编码格式为:' + baiDu_response.encoding)

# 查看当前返回内容    text返回的是字符串
print('Text返回的数据内容为:' + baiDu_response.text)

# 查看当前返回内容    content返回的是字节流
# print('Content返回的数据内容为:' + baiDu_response.content)

# 若返回内容为json格式 可用如下语句
# print('返回的Json数据为:' + baiDu_response.json())

# 获取服务器返回的原始数据 增加stream=True
# data = requests.get('https://api.github.com/events', stream=True)
# print(data.raw.read())

# 发送带参数(字典形式)的get请求
sendDictParams = {'key1': 'value1', 'key2': 'value2'}
baiDu_dictParams_response = requests.get('http://www.baidu.com', params=sendDictParams)

# 查看发送请求的url地址
print('普通参数的get请求地址为: ' + baiDu_dictParams_response.url)

# 发送list格式参数的get请求
sendListParams = {'key1': 'value1', 'key2': ['value2', 'value3']}
baiDu_listParams_response = requests.get('http://www.baidu.com', params=sendListParams)

# 查看发送请求的url地址
print('带list参数的get请求地址为: ' + baiDu_listParams_response.url)

#######################Post请求#######################

# tips:强烈建议使用二进制模式打开文件,因为如果以文本文件格式打开时,可能会因为“Content-Length”这个header而出错
# post 请求参数是通过data方式来传递的

# 第一种方式:字典格式
postResponse = requests.post("http://pythontab.com/postTest", data={'key': 'value'})
print('普通参数请求返回状态码为:' + str(postResponse.status_code))

# 第二种方式 json格式 注意json方法为dumps() 不是dump()
jsonParams = {'key': 'value'}
postJsonResponse = requests.post("http://pythontab.com/postTest", data=json.dumps(jsonParams))
print('json参数请求返回状态码为:' + str(postJsonResponse.status_code))

# 第三种方式 发送文件  (该文件同级目录下需要有test.csv文件 )rb 只读模式  wb 若没有 自动创建
files = {'file': open('test.csv', 'rb')}
fileResponse = requests.post('http://pythontab.com/postTest', files=files)
print('文件参数请求返回状态码为:' + str(fileResponse.status_code))


#######################Headers#######################
headers_response = requests.get('http://www.baidu.com')

# 查看请求响应头 :字典格式 输入时转换为字符打印到控制台
print('请求响应头为: ' + str(headers_response.headers))

# 获取请求响应头其中某一个参数
print('请求响应头的Server参数   写法一:' + headers_response.headers['Server'])

# 等同于
print('请求响应头的Server参数   写法二:' + headers_response.headers.get('Server'))

# 自定义headers 并发送
headers = {'user-agent': 'myAgent'}
custom_headers_response = requests.get('http://www.baidu.com', headers=headers)
print('自定义header发送请求状态码为:' + str(custom_headers_response.status_code))


#######################Cookies#######################
cookies_response = requests.get('http://www.baidu.com')

# 查看请求响应头 :字典格式 输入时转换为字符
print('请求地址的Cookies为: ' + str(cookies_response.cookies))

# 自定义Cookies 并发送
cookies = {'user-cookies': 'myCookies'}
custom_cookies_response = requests.get('http://www.baidu.com', cookies=cookies)
print('自定义Cookies发送请求状态码为:' + str(custom_cookies_response.status_code))

#######################代理#######################

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
# 通过代理方式发起请求 此处运行不通过,仅举例使用
# requests.get("http://baidu.com", proxies=proxies)


#######################Session#######################
# 通过requests获取session
session = requests.Session()
# 举例:登录名 密码  key为登陆表单中对应的input的name值
login_data = {'email': 'email@example.com', 'password': 'password'}
# 发送数据
session.post("http://pythontab.com/testLogin", login_data)
# 获取发送的session
session_response = session.get('http://pythontab.com/notification/')
print('session请求返回的状态码为:' + str(session_response.status_code))

#######################下载页面#######################

baiDuHtmlContent = requests.get("http://www.baidu.com")
with open("百度.html", "wb") as html:
    html.write(baiDuHtmlContent.content)
html.close()

运行结果

这里写图片描述

参考:www.pythontab.com/html/2017/pythonjichu_0510/1138.html

转载于:https://my.oschina.net/u/3648651/blog/1857838


http://www.niftyadmin.cn/n/1336452.html

相关文章

java readutf()方法_Java的DataInputStream的readUTF方法是怎么读取字符串的???

大神们好,我是新手小白,今天在学习Java的IO操作中遇到一个百思不得其解的问题,下面的代码是今天做的关于DataInputStream类的练习,我很不解为什么DataInputStream的readUTF方法不需要任何参数,但是却在读取的时候可以知…

第七课-第一讲07_01_vim编辑器详解

第七课-第一讲07_01_vim编辑器详解 文本编辑器:编辑纯Ascii码的文档,nano全屏编辑,sed行处理,vim字处理器:Word文档,WPS文档等 1.vi编辑器: Visual Interface可视化接口,vi增强版就是vim,vi的基…

通过Powershell调研EWS API删除特定主题邮件操作手册

今天给大家分享一个之前做过的案例,通过Powershell调用Exchange ews API去删除特定主题邮件。【我测试的环境Exchange版本为Exchange 2016】具体的操作过程如下: 1. 说明 通过EWS API去删除特定主题邮件方法,比传统的Search-Mailbox去删除特定…

java url链接超时_Java编程中HttpURLConnection的连接超时中的异常

这是问题所在,我想编写一个Java程序来增加特定URL的页面命中率 . 目前我只是在互联网上浏览并获得一些基本程序来进行测试 . 但是,我甚至无法让程序运行......下面是我的程序和相关输出 .Eclipse,Java程序:URL url new URL("…

聊一聊分布式锁的设计(转)

出处:https://www.cnblogs.com/kingreatwill/p/7344469.html 阅读目录 分布式专家质疑Redlockredis作者解疑Redlock再次分析Redlock起因 前段时间,看到redis作者发布的一篇文章《Is Redlock safe?》,Redlock是redis作者基于redis设计的分布式…

JavaScript基础二

1.7 常用内置对象 所谓内置对象就是ECMAScript提供出来的一些对象,我们知道对象都是有相应的属性和方法 1.7.1 数组Array 1.数组的创建方式 字面量方式创建(推荐大家使用这种方式,简单粗暴)var colors [red,color,yellow]; 使用构…

Java +Tomcat + SpringMVC实现页面访问

2018-07-18 14:38:29window7下Java环境安装记录:一、安装Tomcat1、下载tomcat 7.0,解压,无需安装,放置到目录:D:\apache-tomcat-7.0.90。2、配置系统环境变量,CATALINA_BASED:\apache-tomcat-7.0.90&#x…

超全前端面试题及答案

HTMLCSS 1.对WEB标准以及W3C的理解与认识标签闭合、标签小写、不乱嵌套、提高搜索机器人搜索几率、使用外 链css和js脚本、结构行为表现的分离、文件下载与页面速度更快、内容能被更多的用户所访问、内容能被更广泛的设备所访问、更少的代码和组件,容易维 护、改版方…