我们再来看看前面说的3个步骤:
将首页的url传入,通过RE将源码中相册的网址获取出来
将相册的网址作为url传入
通过RE获取相册中相片的网址
代码如下:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = '217小月月坑'
'''
从第一页跳转到第二页并获得图片的地址
'''
import urllib2
import re
# 极视界首页网址
url = 'http://product.yesky.com/more/506001_31372_photograph_1.shtml'
user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0'
headers = {'User-Agent':user_agent}
try:
request = urllib2.Request(url,headers=headers)
response = urllib2.urlopen(request)
conents = response.read().decode("gbk")
# 获取相册网址和相册名字
pattern = re.compile(r'<dt><a href="(.*?)" title="(.*?)"',re.S)
items = re.findall(pattern,conents)
for info_url in items:
print info_url[0],info_url[1]
# 将相册网址传入
info_response = urllib2.urlopen(info_url[0])
info_conents = info_response.read().decode("gbk")
# 获取图片网址
info_pattern = re.compile(r'<li.*?<img src="(.*?)"',re.S)
img_urls = re.findall(info_pattern,info_conents)
for img_url in img_urls:
print img_url
except urllib2.URLError,e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
e.reason
输出结果: