基于Python模拟浏览器发送http请求


Posted in Python onNovember 06, 2020

1.使用 urllib2 实现

#! /usr/bin/env python
# -*- coding=utf-8 -*- 

import urllib2
url="https://www.baidu.com"
req_header = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Accept":"text/html;q=0.9,*/*;q=0.8",
"Accept-Charset":"ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"Accept-Encoding":"gzip",
"Connection":"close",
"Referer":None #注意如果依然不能抓取的话,这里可以设置抓取网站的host
}
req_timeout = 5
req = urllib2.Request(url,None,req_header)
resp = urllib2.urlopen(req,None,req_timeout)
html = resp.read()
print(html)

2.使用 requests 模块

(1).get请求

#-*- coding:utf-8 -*-
import requests

url = "https://www.baidu.com"
payload = {"key1": "value1", "key2": "value2"}
r = requests.get(url, params=payload)
print r.text

(2).post请求

#-*- coding:utf-8 -*-
import requests
url1 = "http://www.exanple.com/login"#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
      "Accept-Encoding":"gzip",
      "Accept-Language":"zh-CN,zh;q=0.8",
      "Referer":"http://www.example.com/",
      "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
      }
res1 = requests.post(url1, data=data, headers=headers)
res2 = requests.get(url2, cookies=res1.cookies, headers=headers)

print res2.content#获得二进制响应内容
print res2.raw#获得原始响应内容,需要stream=True
print res2.raw.read(50)
print type(res2.text)#返回解码成unicode的内容
print res2.url
print res2.history#追踪重定向
print res2.cookies
print res2.cookies["example_cookie_name"]
print res2.headers
print res2.headers["Content-Type"]
print res2.headers.get("content-type")
print res2.json#讲返回内容编码为json
print res2.encoding#返回内容编码
print res2.status_code#返回http状态码
print res2.raise_for_status()#返回错误状态码

(3).使用session对象的写法

#-*- coding:utf-8 -*-
import requests
s = requests.Session()
url1 = "http://www.exanple.com/login"#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
      "Accept-Encoding":"gzip",
      "Accept-Language":"zh-CN,zh;q=0.8",
      "Referer":"http://www.example.com/",
      "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
      }

prepped1 = requests.Request("POST", url1,
  data=data,
  headers=headers
).prepare()
s.send(prepped1)


"""
也可以这样写
res = requests.Request("POST", url1,
data=data,
headers=headers
)
prepared = s.prepare_request(res)
# do something with prepped.body
# do something with prepped.headers
s.send(prepared)
"""

prepare2 = requests.Request("POST", url2,
  headers=headers
).prepare()
res2 = s.send(prepare2)

print res2.content


"""另一种写法"""
#-*- coding:utf-8 -*-
import requests
s = requests.Session()
url1 = "http://www.exanple.com/login"#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的页面地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
      "Accept-Encoding":"gzip",
      "Accept-Language":"zh-CN,zh;q=0.8",
      "Referer":"http://www.example.com/",
      "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
      }
res1 = s.post(url1, data=data)
res2 = s.post(url2)
print(resp2.content)

3.其他的一些请求方式

>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options(http://httpbin.org/get)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
用python实现批量重命名文件的代码
May 25 Python
浅谈python装饰器探究与参数的领取
Dec 01 Python
VScode编写第一个Python程序HelloWorld步骤
Apr 06 Python
selenium3+python3环境搭建教程图解
Dec 07 Python
Python计算库numpy进行方差/标准方差/样本标准方差/协方差的计算
Dec 28 Python
Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)
Aug 12 Python
Python操作SQLite数据库过程解析
Sep 02 Python
python多进程并发demo实例解析
Dec 13 Python
python json 递归打印所有json子节点信息的例子
Feb 27 Python
OpenCV Python实现拼图小游戏
Mar 23 Python
详解Python遍历列表时删除元素的正确做法
Jan 07 Python
Python  Asyncio模块实现的生产消费者模型的方法
Mar 01 Python
python如何写个俄罗斯方块
Nov 06 #Python
基于Python实现全自动下载抖音视频
Nov 06 #Python
Python3读写ini配置文件的示例
Nov 06 #Python
Python Serial串口基本操作(收发数据)
Nov 06 #Python
python基于exchange函数发送邮件过程详解
Nov 06 #Python
Python Unittest原理及基本使用方法
Nov 06 #Python
python中的yield from语法快速学习
Nov 06 #Python
You might like
无数据库的详细域名查询程序PHP版(1)
2006/10/09 PHP
PHP的ASP防火墙
2006/10/09 PHP
phpExcel中文帮助手册之常用功能指南
2014/08/18 PHP
php实现转换html格式为文本格式的方法
2016/05/16 PHP
PHP addslashes()函数讲解
2019/02/03 PHP
js或css实现滚动广告的几种方案
2010/01/28 Javascript
jquery中animate动画积累的解决方法
2013/10/05 Javascript
Node.js中使用计时器定时执行函数详解
2014/08/15 Javascript
AngularJS入门教程之Hello World!
2014/12/06 Javascript
JavaScript数据类型详解
2015/04/01 Javascript
Bootstrap实现提示框和弹出框效果
2017/01/11 Javascript
jQuery中 bind的用法简单介绍
2017/02/13 Javascript
Ionic + Angular.js实现验证码倒计时功能的方法
2017/06/12 Javascript
前端MVVM框架解析之双向绑定
2018/01/24 Javascript
完美解决axios在ie下的兼容性问题
2018/03/05 Javascript
node实现的爬虫功能示例
2018/05/04 Javascript
使用jQuery给Table动态增加行、清空table的方法
2018/09/05 jQuery
layui lay-verify form表单自定义验证规则详解
2019/09/18 Javascript
小程序实现上下切换位置
2020/11/16 Javascript
[02:39]DOTA2英雄基础教程 天怒法师
2013/11/29 DOTA
Python  pip安装lxml出错的问题解决办法
2017/02/10 Python
浅谈python 线程池threadpool之实现
2017/11/17 Python
Python解决N阶台阶走法问题的方法分析
2017/12/28 Python
解决在pycharm运行代码,调用CMD窗口的命令运行显示乱码问题
2019/08/23 Python
使用python的turtle绘画滑稽脸实例
2019/11/21 Python
Python多线程的退出控制实现
2020/08/10 Python
Python性能测试工具Locust安装及使用
2020/12/01 Python
PyCharm 光标变成黑块的解决方式
2021/02/06 Python
html5 Web SQL Database 之事务处理函数transaction与executeSQL解析
2013/11/07 HTML / CSS
什么时候需要进行强制类型转换
2016/09/03 面试题
移动通信专业自荐信范文
2013/11/12 职场文书
关于工资低的辞职信
2014/01/14 职场文书
物理系毕业生自荐书范文
2014/02/22 职场文书
丧事主持词大全
2014/04/02 职场文书
手术室护士个人总结
2015/02/13 职场文书
煤矿施工安全协议书
2016/03/22 职场文书