Python3爬蟲入門第一課
阿新 • • 發佈:2018-11-09
在印象中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!!!")