简单的爬虫demo

# coding=<encoding name> 例如,可添加# coding=utf-8
import urllib
import re
# 定义一个方法,把整个页面下载下来
def getHtml(url):
    page = urllib.urlopen(url)   # 打开网页
    html = page.read()             #读取 URL上面的数据
    return html                  # 返回内容

# 再定义一个方法,筛选页面中想要的元素,通过正则表达式的匹配
def getimage(html):
    reg = r'src="(.+?.jpg)" pic_ext'   # 定义一个正则表达式
    # re.compile() 把正则表达式编译成一个正则表达式对象
    imagere =re.compile(reg)
    #  re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
    imagerelist = re.findall(imagere,html)
    # 遍历图片
    x = 0
    for imageurl in imagerelist:
        # 这里的核心是用到了urllib.urlretrieve(),方法,直接将远程数据下载到本地
        urllib.urlretrieve(imageurl,'%s.jpg'% x)
        x= x+1


# 调用getHtml 传入一个网址
ht = getHtml("http://tieba.baidu.com/p/2460150866")
# 调用getimage ,拿到图片
print getimage(ht)

运行的效果

原文地址:https://www.cnblogs.com/yuanyuan2017/p/7137162.html