Python3 urllib库和requests库
1. Python3 使用urllib库请求网络
1.1 基于urllib库的GET请求
请求百度首页www.baidu.com ,不添加请求头信息:
import urllib.requests def get_page():
5 url = 'http://www.baidu.com/'
res = urllib.request.urlopen(url=url)
page_source = res.read().decode('utf-8')
print(page_source) if __name__ == '__main__':
get_page()
输出显示百度首页的源码。但是有的网站进行了反爬虫设置,上述代码可能会返回一个40X之类的响应码,因为该网站识别出了是爬虫在访问网站,这时需要伪装一下爬虫,让爬虫模拟用户行为,给爬虫设置headers(User-Agent)属性,模拟浏览器请求网站。
1.2 使用User-Agent伪装后请求网站
由于urllib.request.urlopen() 函数不接受headers参数,所以需要构建一个urllib.request.Request对象来实现请求头的设置:
import urllib.request def get_page():
5 url = 'http://www.baidu.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
9 request = urllib.request.Request(url=url, headers=headers)
res = urllib.request.urlopen(request)
11 page_source = res.read().decode('utf-8')
print(page_source) if __name__ == '__main__':
get_page()
添加headers参数,来模拟浏览器的行为。
1.3 基于urllib库的POST请求,并用Cookie保持会话
登陆ChinaUnix论坛,获取首页源码,然后访问一个文章。首先不使用Cookie看一下什么效果:
import urllib.request
import urllib.parse def get_page():
url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
7 headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
data = {
'username': 'StrivePy',
'password': 'XXX'
}
postdata = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=postdata, headers=headers)
res = urllib.request.urlopen(req)
page_source = res.read().decode('gbk')
18 print(page_source) url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
res1 = urllib.request.urlopen(url=url1)
page_source1 = res1.read().decode('gbk')
print(page_source1) if __name__ == '__main__':
get_page()
搜索源码中是否能看见用户名StrivePy,发现登陆成功,但是再请求其它文章时,显示为游客状态,会话状态没有保持。现在使用Cookie看一下效果:
import urllib.request
import urllib.parse
import http.cookiejar def get_page():
url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
data = {
'username': 'StrivePy',
'password': 'XXX'
}
postdata = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=postdata, headers=headers)
# 创建CookieJar对象
cjar = http.cookiejar.CookieJar()
# 以CookieJar对象为参数创建Cookie
cookie = urllib.request.HTTPCookieProcessor(cjar)
# 以Cookie对象为参数创建Opener对象
opener = urllib.request.build_opener(cookie)
23 # 将Opener安装位全局,覆盖urlopen函数,也可以临时使用opener.open()函数
24 urllib.request.install_opener(opener)
res = urllib.request.urlopen(req)
page_source = res.read().decode('gbk')
print(page_source) url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
res1 = urllib.request.urlopen(url=url1)
page_source1 = res1.read().decode('gbk')
print(page_source1) if __name__ == '__main__':
get_page()
结果显示登陆成功后,再访问其它文章时,显示为登陆状态。若要将Cookie保存为文件待下次使用,可以使用MozillaCookieJar对象将Cookie保存为文件。
import urllib.request
import urllib.parse
import http.cookiejar def get_page():
url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
data = {
'username': 'StrivePy',
'password': 'XXX'
}
postdata = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=postdata, headers=headers)
filename = 'cookies.txt'
# 创建CookieJar对象
cjar = http.cookiejar.MozillaCookieJar(filename)
# 以CookieJar对象为参数创建Cookie
cookie = urllib.request.HTTPCookieProcessor(cjar)
# 以Cookie对象为参数创建Opener对象
opener = urllib.request.build_opener(cookie)
# 临时使用opener来请求
opener.open(req)
# 将cookie保存为文件
cjar.save(ignore_discard=True, ignore_expires=True)
会在当前工作目录生成一个名为cookies.txt的cookie文件,下次就可以不用登陆(如果cookie没有失效的话)直接读取这个文件来实现免登录访问。例如不进行登陆直接访问其中一篇文章(没登陆也可以访问,主要是看抬头是不是登陆状态):
import http.cookiejar def get_page():
url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
filename = 'cookies.txt'
cjar = http.cookiejar.MozillaCookieJar(filename)
cjar.load(ignore_discard=True, ignore_expires=True)
cookie = urllib.request.HTTPCookieProcessor(cjar)
opener = urllib.request.build_opener(cookie)
res1 = opener.open(url1)
page_source1 = res1.read().decode('gbk')
print(page_source1) if __name__ == '__main__':
get_page()
结果显示是以登陆状态在查看这篇文章。
1.4 基于urllib库使用代理请求
使用代理可以有效规避爬虫被封。
import urllib.request def proxy_test():
url = 'http://myip.kkcha.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
request = urllib.request.Request(url=url, headers=headers)
proxy = {
'http': '180.137.232.101:53281'
}
# 创建代理Handler对象
proxy_handler = urllib.request.ProxyHandler(proxy)
# 以Handler对象为参数创建Opener对象
opener = urllib.request.build_opener(proxy_handler)
# 将Opener安装为全局
urllib.request.install_opener(opener)
response = urllib.request.urlopen(request)
page_source = response.read().decode('utf-8')
print(page_source) if __name__ == '__main__':
proxy_test()
抓取到的页面应该显示代理IP,不知道什么原因,有时候能正常显示,有时候跳转到有道词典广告页!!!问题有待更进一步研究。
2. Python3 使用requsets库访问网络
2.1 基于requests库的GET请求
以GET方式请求http://httpbin.org测试网站。
import requests def request_test():
url = 'http://httpbin.org/get'
response = requests.get(url)
print(type(response.text), response.text)
print(type(response.content), response.content) if __name__ == '__main__':
request_test()
直接得到响应体。
<class 'str'> {"args":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"origin":"121.61.132.191","url":"http://httpbin.org/get"} <class 'bytes'> b'{"args":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"origin":"121.61.132.191","url":"http://httpbin.org/get"}\n
在GET方法中传递参数的三种方式:
- 将字典形式的参数用urllib.parse.urlencode()函数编码成url参数:
import urllib.parse if __name__ == '__main__':
base_url = 'http://httpbin.org/'
params = {
'key1': 'value1',
'key2': 'value2'
}
full_url = base_url + urllib.parse.urlencode(params)
print(full_url)http://httpbin.org/key1=value1&key2=value2
- 直接在urllib.request.get()函数中使用params参数:
import requests if __name__ == '__main__':
payload = {
'key1': 'value1',
'key2': 'value2'
}
response = requests.get('http://httpbin.org/get', params=payload)
print(response.url)http://httpbin.org/key1=value1&key2=value2
- url直接包含参数:
http://httpbin.org/get?key2=value2&key1=value1
2.2 基于requests库的POST请求,并用session保持会话
登陆ChinaUnix论坛,获取首页源码,然后访问一个文章。首先不使用Session看一下什么效果:
import requests def get_page():
6 url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
data = {
11 'username': 'StrivePy',
'password': 'XXX'
}
response = requests.post(url=url, data=data, headers=headers)
page_source = response.text
print(response.status_code)
print(page_source) url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
response1 = requests.get(url=url1, headers=headers)
page_source1 = response1.text
print(response1.status_code)
print(page_source1) if __name__ == '__main__':
get_page()
结果显示访问其它文章时为游客模式。接下来用session来维持会话看一下效果:
import requests def get_page():
url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
data = {
'username': 'StrivePy',
'password': 'XXX'
}
session = requests.session()
response = session.post(url=url, data=data, headers=headers)
page_source = response.text
print(response.status_code)
print(page_source) url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
response1 = session.get(url=url1, headers=headers)
page_source1 = response1.text
22 print(response1.status_code)
print(page_source1) if __name__ == '__main__':
get_page()
结果显示访问其它文章时,显示为登陆状态,会话保持住了。使用session的效果类似于urllib库临时使用opener或者将opener安装为全局的效果。
2.3 基于requests库使用代理请求
在requests库中使用代理:
import requests def proxy_test():
url = 'http://myip.kkcha.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
proxy = {
'https': '61.135.217.7: 80'
}
response = requests.get(url=url, headers=headers, proxies=proxy)
print(response.text) if __name__ == '__main__':
proxy_test()
这个请求到的代码显示IP还是本地的网络IP,代理没起作用,具体原因有待研究。
Python3 urllib库和requests库的更多相关文章
- python3好用的requests库
python3好用的requests库 requests是什么? requests是基于urllib编写的http库,支持python3,比urllib更好用,更简单.之前使用python写一些htt ...
- 【Python爬虫】HTTP基础和urllib库、requests库的使用
引言: 一个网络爬虫的编写主要可以分为三个部分: 1.获取网页 2.提取信息 3.分析信息 本文主要介绍第一部分,如何用Python内置的库urllib和第三方库requests库来完成网页的获取.阅 ...
- python库:bs4,BeautifulSoup库、Requests库
Beautiful Soup https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ Beautiful Soup 4.2.0 文档 htt ...
- [python爬虫]Requests-BeautifulSoup-Re库方案--Requests库介绍
[根据北京理工大学嵩天老师“Python网络爬虫与信息提取”慕课课程编写 文章中部分图片来自老师PPT 慕课链接:https://www.icourse163.org/learn/BIT-10018 ...
- 爬虫请求库之requests库
一.介绍 介绍:使用requests可以模拟浏览器的请求,比之前的urllib库使用更加方便 注意:requests库发送请求将网页内容下载下来之后,并不会执行js代码,这需要我们自己分析目标站点然后 ...
- 请求库之requests库
目录 一.介绍 二.基于get请求 1 基本请求 2 带参数的get请求 3 请求携带cookie 三.基于post请求 1 基本用法 2 发送post请求,模拟浏览器的登录行为 四.响应Respon ...
- requests库和urllib包对比
python中有多种库可以用来处理http请求,比如python的原生库:urllib包.requests类库.urllib和urllib2是相互独立的模块,python3.0以上把urllib和ur ...
- python关于urllib库与requests
对于这两个库来说个人推荐使用requests库 下面用实例来说明 urllib库: requests库: 实现同样功能: 实现同样的功能下urllib比request步骤更复杂,这个对于我们编程来说是 ...
- python3.5 使用tkinter 和requests库实现天气图像化显示
1 """ 该python小例子考察使用了tkinter库,requests库 其中: requests库用来发送网络请求 thkinter用来显示图形化界面 请求的天气 ...
随机推荐
- PS前端
学习使用Photoshop的基本使用,以及Photoshop中关于切图这一块的知识,目的是能熟练使用Photoshop查看UI设计师的设计效果图,同时利用Photoshop切图来制作专业html页面. ...
- HAproxy使用
参考官网 安装HAproxy/ pull 官方镜像 本地安装:本地安装路径:/usr/local/haproxy/配置: 添加:/usr/local/haproxy/conf/haproxy.cfg添 ...
- Spring MVC @InitBinder 数据绑定 & 数据格式化 & 数据校验
1 数据绑定 2 数据格式化 修改绑定的字段等等操作 日期 - 接收表单日期字符串格式内容.,在实体类加入@DateTimeFormat 数值 原理: DefautFormattingConversi ...
- 4 并发编程-(进程)-守护进程&互斥锁
一.守护进程 主进程创建子进程,然后将该进程设置成守护自己的进程,守护进程就好比崇祯皇帝身边的老太监,崇祯皇帝已死老太监就跟着殉葬了. 关于守护进程需要强调两点: 其一:守护进程会在主进程代码执行结束 ...
- 【Web缓存机制系列】2 – Web浏览器的缓存机制
Web缓存的工作原理 所有的缓存都是基于一套规则来帮助他们决定什么时候使用缓存中的副本提供服务(假设有副本可用的情况下,未被销毁回收或者未被删除修改).这些规则有的在协议中有定义(如HTTP协议1.0 ...
- PL/SQL Developer安装教程以及汉化包安装教程
一.安装PL/SQL 1.百度下载plsql破解版软件,官网只能使用30天 2.双击plsqldev906.exe进行安装,点击 iagree 3.默认是安装在c盘,可以根据自己需要更改安装目录 4. ...
- cobbler配置解析
1.Cobbler命令说明: 命令名称 命令用途 cobbler check 检查cobbler配置 cobbler list 列出所有的cobbler元素 cobbler report 列出元素的详 ...
- Java Magic. Part 3: Finally
Java Magic. Part 3: Finally @(Base)[JDK, magic, 黑魔法] 转载请写明:原文地址 英文原文 系列文章: -Java Magic. Part 1: java ...
- 【Java】JVM(五)、虚拟机类加载机制
一.概念 类加载:虚拟机把类的数据从Class文件加载到内存中,并对数据进行校验,转化解析,和初始化,最终形成可以被虚拟机直接使用的Java类型. 二.加载时机 1.加载 加载阶段虚拟机完成的工作为: ...
- 好用的模板引擎NVelocity
CastleNVelocity-1.1.1,使用方法: 把dll放到项目中,添加引用,修改配置的文件夹以及数据模型,最后在逻辑代码中调用即可. 封装到CommonHelper.cs using Sys ...