1. 程式人生 > >python第一個爬蟲程式

python第一個爬蟲程式

 轉載https://www.cnblogs.com/Axi8/p/5757270.html

把python2的部分改成python3了,爬取百度貼吧某帖子內的圖片。

    #coding:utf-8
    import urllib.request#python3
    import re
    
    def get_html(url):
        page = urllib.request.urlopen(url)#開啟網頁
        html = page.read()#讀取頁面原始碼
        #html = html.decode(encoding='UTF-8')#python3
        html=html.decode('utf-8')#python3
        return html
        
    
    reg = r'src="(.+?\.jpg)" width'#正則表示式
    reg_img = re.compile(reg)#編譯一下,執行更快
    imglist = reg_img.findall(get_html('http://tieba.baidu.com/p/1753935195'))#進行匹配
    x = 0
    for img in imglist:
        urllib.request.urlretrieve(img,'%s.jpg'% x)
        x += 1