很久没有用python了,心血来潮写一下自己对于学习python获取网络数据的总结。
工具
python版本: 3.5
IDE : pycharm 5.0.4
要用到的包可以用pycharm下载:
File->Default Settings->Default Project->Project Interpreter
选择python版本并点右边的加号安装想要的包
这里以爬取图片为例:
获取目的网站的信息:
#coding=utf-8 //中文编码
import urllib2
url = "http://tieba.baidu.com/p/2738151262"
def getHtml():
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read()
return html
urllib2 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取www和ftp上的数据。首先,我们定义了一个getHtml()函数:
urllib2.urlopen()方法用于打开一个URL地址。
read()方法用于读取URL上的数据,向getHtml()函数传递一个网址,并把整个页面下载下来。返回结果。
利用正则表达式对爬取的网页进行筛选
审查图片元素,观察我们要获取的图片对应的网页代码是什么样的!!!
添加代码
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
return imglist
re.compile() 可以把正则表达式编译成一个正则表达式对象.
re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
运行脚本将得到整个页面中包含图片的URL地址。
将页面筛选的数据保存到本地
使用for循环
修改代码如下:
#coding=utf-8
import urllib2
url = "http://tieba.baidu.com/p/2738151262"
def getHtml():
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read()
return html
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
x = 0
for imgurl in imglist:
urllib.urlretrieve(imgurl,'%s.jpg' % x)
x+=1
if __name__ == "__main__":
html = getHtml()
getImg(html)
或者
//注意aw与w的区别
with open('out.txt','aw') as file:
file.write('%s\n' % imgurl)
//图片对应的url