Python3爬虫入门第一课

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36092584/article/details/81192078

在印象中Python就是用来抓数据的,这次用的Python3.7,发现和以前的2.x的版本语法差别还是很大的,因为没有进行版本兼容。

# coding:utf-8
import urllib.request 
import re

def get_html(url):
	page = urllib.request.urlopen(url)
	html = page.read() #注意read和write方法都是获取到字节码的
	return html
	
def get_image(htmlcode):
	reg = r'src="(.+?\.jpg)" width' #正则表达式 惰性匹配是从左侧第一个字符开始向右匹配
	reg_img = re.compile(reg) #编译
	imglist = reg_img.findall(htmlcode.decode('utf-8'))
	x = 0
	for img in imglist:
		urllib.request.urlretrieve(img, 'C:\\Users\\10129\\Desktop\\python\\img\\%s.jpg' %x)
		print(img)
		x += 1	
	
#写到txt里面去
def write2txt(htmlcode):
	pageFile = open("C:\\Users\\10129\\Desktop\\python\\pageCode.txt","wb+")
	pageFile.write(htmlcode)
	pageFile.close()

print ("--------网页图片抓取---------")
print ("请输入url:"),
url = input()
if url:
	pass  # 不做任何事情,用作占位符
else:
	print ("-----没有地址使用默认地址-------")
	url = 'http://tieba.baidu.com/p/1753935195'
htmlcode = get_html(url)
write2txt(htmlcode)
get_image(htmlcode)
print("FINISH!!!")


猜你喜欢

转载自blog.csdn.net/qq_36092584/article/details/81192078