您的位置:首页 > 编程语言 > Python开发

python爬虫实例

2015-10-20 19:08 253 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/lyq2013/article/details/49281299

本文用一个简单的例子说明如何用python进行爬虫。

  • python 2.7.5
  • Ubuntu 14.04

所需的python库

  • urllib:用来抓取和解析网页
  • re:处理正则表达式

代码块

  • 下面的例子是用python爬虫获取某网页的图片,并保存到本地
import urllib
import re
import os

def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html

def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre, html)

# save the pics to a new folder.
os.mkdir('pics')
local = os.getcwd() + '/pics/'
x = 0

for imgurl in imglist:
urllib.urlretrieve(imgurl, local + '%s.jpg' % x)
x += 1

html = getHtml("http://tieba.baidu.com/p/2460150866")

print getImg(html)
  • 对正则表达式不熟悉的话可以学习一下相关知识
  • 运行该程序后会在pics目录下看到下载好的jpg图片

源文件在这里

  • python爬虫的功能很强大,可以根据所需信息的不同对正则表达式进行修改
  • 对爬取的数据可以依据数据挖掘的方式进行处理
  • 源文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: