1. 程式人生 > >Python練習四:爬取圖片

Python練習四:爬取圖片

貼吧地址

https://tieba.baidu.com/p/5272413637?red_tag=0606091703

 

程式如下
import urllib.request
import re

def open_url(url):
  req = urllib.request.Request(url)
  req.add_header('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36')

  page = urllib.request.urlopen(req)
  html = page.read().decode('utf-8')
  return html

def get_img(html):
  p = r'<img class="BDE_Image" src="([^"]+\.jpg)"'
  imglist = re.findall(p, html)

  for each in imglist:
    file_name = each.split('/')[-1]
    urllib.request.urlretrieve(each, file_name)
if __name__ == '__main__':
  url = '

https://tieba.baidu.com/p/5272413637?red_tag=0606091703'
  get_img(open_url(url))

執行程式結果