您的位置:首页 > 编程语言 > Python开发

python——基于煎蛋网的简单图片爬虫

2017-04-11 17:26 573 查看
import urllib.request
import os

def get_url(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8','ignore')

a=html.find('current-comment-page')+23
b=html.find(']',a)

return html[a:b]

def find_url(page_url):
req = urllib.request.Request(page_url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8','ignore')

url_list=[]

a=html.find('img src=')

while a != -1:
b=html.find('.jpg',a,a+255)
if b != -1:
url_list.append(html[a+9:b+4])
else :
b=a+9
a=html.find('img src=',b)

return url_list

def save_pic(folder,list):
for each in list :
filename=each.split('/')[-1]
with open(filename,'wb') as f:
each='http:'+each
req = urllib.request.Request(each)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read()
f.write(html)

def download(file='demo',page=10):
os.mkdir(file)
os.chdir(file)

url='http://jandan.net/ooxx/'

page_num=int(get_url(url))
for i in range(page):
page_num -= i
page_url=url+'page-'+str(page_num) +'#comments'
list=find_url(page_url)
save_pic(file,list)

if __name__=='__main__':
download()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: