Python模拟浏览器发送http请求

Python模拟浏览器发送http请求

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")
 
 

Tags: http   http请求   python   发送   模拟   

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Python实现模拟浏览器请求及会话保持操作示例

 更新时间:2018年07月30日 10:05:37   作者:初行   我要评论
 
这篇文章主要介绍了Python实现模拟浏览器请求及会话保持操作,结合实例形式分析了Python基于urllib与urllib2模块模拟浏览器请求及cookie保存会话相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python实现模拟浏览器请求及会话保持操作。分享给大家供大家参考,具体如下:

python下读取一个页面的数据可以通过urllib2轻松实现请求

?
1
2
import urllib2
print urllib2.urlopen( 'http://www.baidu.com' ).read()

涉及到页面的POST请求操作的话需要提供头信息,提交的post数据和请求页面。

其中的post数据需要urllib.encode()一下,其实就是将字典转换成“data1=value1&data2=value2”的格式。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import urllib
import urllib2
HEADER = {
  'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0' ,
}
POSTDATA = {
  'data1' : 'value1' ,
  'data2' : 'value2'
}
HOSTURL = 'http://xxx.com'
enpostdata = urllib.urlencode(POSTDATA)
urlrequest = urllib2.Request(hosturl,enpostdata,HEADER)
urlresponse = urllib2.urlopen(urlrequest)
print urlresponse.read()

请求之后浏览器会有一个会话保持的过程,会话都是保存在一个cookie里面的,下一次页面的请求会把cookie放到请求头,如果cookie丢失会话也就断开了。

在python下面需要设置一下cookie的保持

?
1
2
3
4
5
6
# cookie set
# 用来保持会话
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)

下面是将以上知识点汇总写的一个库文件,方便使用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# filename: analogop.py
#!/usr/bin/python
# -*-coding:UTF-8 -*-
# author: 初行
# qq: 121866673
# message: I need a python job
# time: 2014/10/5
import urllib
import urllib2
import cookielib
# cookie set
# 用来保持会话
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
# default header
HEADER = {
  'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0' ,
}
# operate method
def geturlopen(hosturl, postdata = {}, headers = HEADER):
  # encode postdata
  enpostdata = urllib.urlencode(postdata)
  # request url
  urlrequest = urllib2.Request(hosturl, enpostdata, headers)
  # open url
  urlresponse = urllib2.urlopen(urlrequest)
  # return url
  return urlresponse

这个是测试文件,因为读者没有测试环境,需要自己搭建或者找个网站测试:

?
1
2
3
4
5
6
7
8
9
10
11
12
#filename: test.py
from analogop import geturlopen
postd = {
  'usernum' : '2011411111' ,
  'upw' : '124569' ,
  'userip' : '192.168.10.1' ,
  'token' : 'xxx'
}
urlread = geturlopen( 'http://127.0.0.1:8000/login/' , postd)
print urlread.read().decode( 'utf-8' )
urlread = geturlopen( 'http://127.0.0.1:8000/chafen/' , {})
print urlread.read().decode( 'utf-8' )

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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")

猜你喜欢

转载自www.cnblogs.com/xinxihua/p/12819997.html