今天刚稍微学了点python,找了个简单的爬虫学习一下。
这个是简单爬取贴吧帖子图片的一个小内容,主要就是获取网址,得到源码,找出其中的图片链接,并下载。
接下来,正文:
coding:utf-8
import urllib
import re
page = urllib.urlopen(‘http://tieba.baidu.com/p/1753935195’)
htmlcode = page.read()
print htmlcode
def get_html(url):
page = urllib.urlopen(url)
html = page.read()
return html
def get_img(html_code):
reg = r’src="(.+?.jpg)" width’
reg_img = re.compile(reg) #编译一下,运行更快
imglist = reg_img.findall(get_html(‘http://tieba.baidu.com/p/1753935195’))
img_count = 0
for img in imglist:
urllib.urlretrieve(img, ‘img/%s.jpg’ %img_count)
img_count += 1
print u’请输入url:’
url = raw_input()
if url:
pass
else:
url = ‘http://tieba.baidu.com/p/1753935195’
html_code = get_html(url)
get_img(html_code)