最最最最简单的python爬虫操作
最近初学了python,就尝试了一下非常简单的爬虫(爬取网页的图片存到本机上)。适合开始学习python的小白。
环境:python3.0。
上代码:
import re
import urllib.request
def get_content(url):
# 定义一个抓取的函数
html =urllib.request.urlopen(url)
content =html.read().decode('utf-8')
html.close()
return content
def get_images(info):
# 定义一个保存图片到本地的函数
src =r'<img class="BDE_Image" src="(.+?\.jpg)"'
comp =re.compile(src)
get_codes =re.findall(comp,info)
i = 1
for get_code in get_codes:
urllib.request.urlretrieve(get_code,r'D:\pythonPicture\%s.jpg'%i)#地址为绝对路径
i =i + 1
info =get_content('http://tieba.baidu.com/p/5914519867') # 爬取图片的网页链接
get_images(info)
print("完成") #完成
运行如下: