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用来显示图形化界面 请求的天气 ...
随机推荐
- uva-193-图染色-枚举
题意:n个节点,可用描成黑色或者白色,黑节点和黑节点不能相连,问最多描出多少黑节点 #include <iostream> #include <stdio.h> #includ ...
- activemq的学习
https://blog.csdn.net/csdn_kenneth/article/category/7352171/1
- springboot之登录注册
springboot之登录注册 目录结构 pom.xml <?xml version="1.0" encoding="UTF-8"?> <pr ...
- leetcode191
public class Solution { public int HammingWeight(uint n) { var list = new List<uint>(); do { ; ...
- jetty异常
异常一: java.net.BindException: Address already in use: bind jvm 1 | 2017-10-18 15:08:10,792+0800 WARN ...
- 11 python shutil 模块
shutil 模块 高级的 文件.文件夹.压缩包 处理模块 1.将文件内容拷贝到另一个文件中 import shutil f1 = open('os_模块.py','r',encoding='ut ...
- jstatd - Virtual Machine jstat Daemon
jstatd [options] 参数:options 命令行参数,可以按任何顺序,但如果有多余的或者中有互斥的参数,最后制定的那个参数将有优先权 options: -nr 当一个存在的RMI Reg ...
- Java静态初始化,实例初始化以及构造方法
首先有三个概念需要了解: 一.静态初始化:是指执行静态初始化块里面的内容. 二.实例初始化:是指执行实例初始化块里面的内容. 三.构造方法:一个名称跟类的名称一样的方法,特殊在于不带返回值. 我们先来 ...
- 常用类一一MATH类一一两个静态常量PI 和E,一些数学函数。
package test; public class MathTest { public static void main(String[] args) { System.out.println(Ma ...
- JSP复习(part 3 )
3.4.4 request对象提供了一些用来获取客户信息的方法,利用这些方法,可以获取客户端的IP地址 协议等有关信息 3.5 request对象和response对象相对应,用于响应客户请求,由服务 ...