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用来显示图形化界面 请求的天气 ...
随机推荐
- selenium+python自动化91-unittest多线程生成报告(BeautifulReport)
前言 selenium多线程跑用例,这个前面一篇已经解决了,如何生成一个测试报告这个是难点,刚好在github上有个大神分享了BeautifulReport,完美的结合起来,就能生成报告了. 环境必备 ...
- spring securiry Xml 配置 登陆
参考:https://blog.csdn.net/yin380697242/article/details/51893397 https://blog.csdn.net/lee353086/artic ...
- 数据库中的html在页面上显示
在ASP页面中,动态显示html格式的数据的方法如下: .aspx文件: <div id="divBox" runat="server"></ ...
- eclipse override报错
转自:https://www.cnblogs.com/libra0920/p/6408891.html 错误: 在 eclipse 的新工作空间开发项目时,出现大面积方法编译错误.鼠标放在方法名上后显 ...
- shiro 与spring的集成
1.导入spring与shiro的jar包 2.在web.xml 文件中配置shiro的shiroFilter <filter> <filter-name>shiroFilte ...
- 怎么才能将文件流或者图片转化为base64,传到前台展示
图片转化为base64,传到前台展示 public String getBase64(){ String imgStr = ""; try { File file = new Fi ...
- as3 加载gif loader
as3原生不支持gif动态图 loader 加载gif ,内容只是以bitmap加载进来 需要动态,另外衍生类: https://files.cnblogs.com/files/dt1991/GifL ...
- 启动startUML的时候报错“"Exception EOleSysError in module StarUML.exe at 000AD559. "
win7操作系统在安装startuml的时候总是报错 出现了如下错误提示:"Exception EOleSysError in module StarUML.exe at 000AD559. ...
- Unity C# 调用 C++ DLL 并在 DLL 中调用 C# 的回调函数
Unity C# 调用 C++ DLL 并在 DLL 中调用 C# 的回调函数~~~ 呵呵... 看着有点晕.. 再解释一下就是 在Unity中 使用 C# 调用 C++ 写的 DLL, 但是在 ...
- 注册COM
可以用代码在程序中实现COM的注册. 举例如下: (假设需要注册的文件为test.ocx)uses OLEctl,....varOCXHand: THandle;RegFunc: TDllRegist ...