本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于python爬虫如何爬取get请求的页面数据(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
一.urllib库
urllib是Python自带的一个用于爬虫的库,其主要作用就是可以通过代码模拟浏览器发送请求。其常被用到的子模块在Python3中的为urllib.request和urllib.parse,在Python2中是urllib和urllib2。
二.由易到难的爬虫程序:
1.爬取百度首页面所有数据值
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#导包
import urllib.request
import urllib.parse
if __name__ == "__main__" :
#指定爬取的网页url
url = 'http://www.baidu.com/'
#通过urlopen函数向指定的url发起请求,返回响应对象
reponse = urllib.request.urlopen(url=url)
#通过调用响应对象中的read函数,返回响应回客户端的数据值(爬取到的数据)
data = reponse.read()#返回的数据为byte类型,并非字符串
print (data)#打印显示爬取到的数据值。
|
#补充说明
urlopen函数原型:
1 | urllib.request.urlopen(url, data=None, timeout=<object object at 0x10af327d0>, *, cafile=None, capath=None, cadefault=False, context=None)
|
在上述案例中我们只使用了该函数中的第一个参数url。在日常开发中,我们能用的只有url和data这两个参数。
url参数:指定向哪个url发起请求
data参数:可以将post请求中携带的参数封装成字典的形式传递给该参数(暂时不需要理解,后期会讲)
urlopen函数返回的响应对象,相关函数调用介绍:
response.headers():获取响应头信息
response.getcode():获取响应状态码
response.geturl():获取请求的url
response.read():获取响应中的数据值(字节类型)
2.将爬取到百度新闻首页的数据值写入文件进行存储
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import urllib.parse
if __name__ == "__main__" :
url = 'http://news.baidu.com/'
reponse = urllib.request.urlopen(url=url)
#decode()作用是将响应中字节(byte)类型的数据值转成字符串类型
data = reponse.read().decode()
#使用IO操作将data表示的数据值以 'w' 权限的方式写入到news.html文件中
with open( './news.html' , 'w' ) as fp:
fp.write(data)
print ( '写入文件完毕' )
|
3.爬取网络上某张图片数据,且存储到本地
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import urllib.parse
#如下两行代码表示忽略https证书,因为下面请求的url为https协议的请求,如果请求不是https则该两行代码可不用。
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
if __name__ == "__main__" :
#url是https协议的
url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536918978042&di=172c5a4583ca1d17a1a49dba2914cfb9&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F0dd7912397dda144f04b5d9cb9b7d0a20cf48659.jpg'
reponse = urllib.request.urlopen(url=url)
data = reponse.read()#因为爬取的是图片数据值(二进制数据),则无需使用decode进行类型转换。
with open( './money.jpg' , 'wb' ) as fp:
fp.write(data)
print ( '写入文件完毕' )
|
4.url的特性:url必须为ASCII编码的数据值。所以我们在爬虫代码中编写url时,如果url中存在非ASCII编码的数据值,则必须对其进行ASCII编码后,该url方可被使用。
阅读剩余部分
相关阅读 >>
Python学什么方向
Python中大数据处理详解
Python爬虫如何设置代理
Python注释以什么符号开始
Python怎么输入数字
Python怎么用c++代码
Python如何实现猜数字游戏
Python items()方法如何使用
Python英文怎么读
Python连接mysql的方式总结
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python爬虫如何爬取get请求的页面数据?(附代码)