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

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()
		
		
		
		

你可能感兴趣的:(python——基于煎蛋网的简单图片爬虫)