fatalman 发表于 2020-5-5 10:11:07

图片下载报错

执行错误和代码如下,求大神帮忙看看代码哪里有错
Traceback (most recent call last):
File "D:\Program Files\Python38\Code\get_picture.py", line 26, in <module>
    get_img(open_url(url))
File "D:\Program Files\Python38\Code\get_picture.py", line 17, in get_img
    urllib.request.urlretrieve(each,filename,None)
File "D:\Program Files\Python38\lib\urllib\request.py", line 247, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
File "D:\Program Files\Python38\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
File "D:\Program Files\Python38\lib\urllib\request.py", line 525, in open
    response = self._open(req, data)
File "D:\Program Files\Python38\lib\urllib\request.py", line 547, in _open
    return self._call_chain(self.handle_open, 'unknown',
File "D:\Program Files\Python38\lib\urllib\request.py", line 502, in _call_chain
    result = func(*args)
File "D:\Program Files\Python38\lib\urllib\request.py", line 1390, in unknown_open
    raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: <img class="bde_image" src="https>



import urllib.request
import re

def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.220 Safari/535.1')
    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:
      filename = each.split('/')[-1]
      urllib.request.urlretrieve(each,filename,None)

'''
    for each in imglist:
      print(each)
'''

if __name__ == '__main__':
    url = 'https://tieba.baidu.com/p/3956076296'
    get_img(open_url(url))

suchocolate 发表于 2020-5-5 21:55:57

本帖最后由 suchocolate 于 2020-5-5 21:57 编辑

p = r'class="BDE_Image" src="(.*?\.jpg)"'

MIke_python小小 发表于 2020-5-12 17:43:48

p = r'class="BDE_Image" src="(.*?\.jpg)"'

这个最佳吧
页: [1]
查看完整版本: 图片下载报错