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用来显示图形化界面 请求的天气 ...
随机推荐
- mysql数据库的维护,备份和复制
在数据库运行时维护数据库 执行mysql数据库维护的方法之一就是连接mysql服务器,并告诉它做什么事, 如对myisam数据表进行检查或者修复, 可以使用check table tbname或rep ...
- 解决maven工程 子工程中的一些配置读取进来的问题
方案:在父工程中手动配置一些节点 <build> <!-- 插件 --> <plugins> <plugin> <groupId>org.a ...
- Jsch - java SFTP 文件上传下载
使用Jsch上传.下载文件,核心步骤是:获取channel,然后使用get/put方法下载.上传文件 核心代码句: session = jSch.getSession(ftpUserName, ftp ...
- jquery 隐藏 显示 动画效果
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js&qu ...
- random内置模块
import random random.random() #生成0-1的随机浮点数 random.randint(1, 10) #生成1-10的整数 random.randrange(1,10) # ...
- Spring MVC 运行流程图
- npm 安装cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
- UI5-文档-4.9-Component Configuration
在我们介绍了模型-视图-控制器(MVC)概念的所有三个部分之后,现在我们将讨论SAPUI5的另一个重要的结构方面. 在这一步中,我们将把所有UI资产封装在一个独立于索引的组件中.html文件.组件是S ...
- C#怎么判断字符是不是汉字
.用ASCII码判断 在 ASCII码表中,英文的范围是0-,而汉字则是大于127,根据这个范围可以判断,具体代码如下: string text = "我去"; bool res ...
- 转载:阿里canal实现mysql binlog日志解析同步redis
from: http://www.cnblogs.com/duanxz/p/5062833.html 背景 早期,阿里巴巴B2B公司因为存在杭州和美国双机房部署,存在跨机房同步的业务需求.不过早期的数 ...