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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章