用python爬取愛課程首頁所有的圖片並下載到本地__python

來源:互聯網
上載者:User

分析:因為是要下載所有的圖片,不需要進行篩選。這就簡單多了。圖片一般都在“src=”的後面。

代碼:

# -*- coding:utf-8 -*-__author__ = 'Bohn'import requests, re, osfrom urllib.request import urlretrievedef getHtml(url):    #偽裝頭部    user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'    headers = {'User-Agent': user_agent}    response = requests.get(url)    response.encoding = 'utf-8'    html = response.text    print("Got html")    return htmldef getImg(html):    #編寫Regex    regex = 'src="(.*?)"'     pattern = re.compile(regex, re.S)    #找到Regex匹配的圖片    imglist = re.findall(pattern, html)    print(imglist)    x = 1    #判斷這個檔案夾是否存在,不存在就建立    if not(os.path.exists(r'D:\imgsaving')):        os.makedirs(r'D:\imgsaving')    #下載圖片    for img in imglist:        print("正在下載第%s張圖片…" % x)        urlretrieve(img, r'D:\imgsaving\%s.jpg' % x)        x = x + 1    returntry:    #爬取愛課程首頁的圖片    url = r"http://www.icourses.cn/home/"    html = getHtml(url)    getImg(html)    print("OK")except:    print('Failed.')

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.