码迷,mamicode.com
首页 > 编程语言 > 详细

python3的一个简单爬虫

时间:2017-07-21 18:55:25      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:div   utf-8   eth   接口   正则表达式   findall   reg   打开   eve   

 #coding=utf-8
import re
import urllib.request
def getHtml(url):
    page = urllib.request.urlopen(url)
    html = page.read()
    html = html.decode(UTF-8)
    return html
#Urllib 模块提供读取页面数据的接口
#urllib.request.urlopen()方法用于打开一个url地址
#read()方法用于读取url上的数据
print(getHtml("http://tieba.baidu.com/p/2460150866"))

def getImg(html):
    reg = rsrc="(.+?\.jpg)" pic_ext
    imgre = re.compile(reg)
#re.compile()可以把正则表达式编译成一个正则表达式对象
    imglist = re.findall(imgre, html)
#re.findall()方法读取html中包含imgre(正则表达式)的数据
    num = 0
    for imgurl in imglist:
        urllib.request.urlretrieve(imgurl,%s.jpg % num)
#urllib.request.urlretrieve()方法,直接将远程数据下载到本地
        num+=1
        if num>10:
            return num

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

 

python3的一个简单爬虫

标签:div   utf-8   eth   接口   正则表达式   findall   reg   打开   eve   

原文地址:http://www.cnblogs.com/cc233/p/7219055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!