huahua_0917 发表于 2020-4-5 13:45:21

写出的爬图py老是出错,请指正

本帖最后由 huahua_0917 于 2020-4-5 15:54 编辑

根据小甲鱼书上和网站视频讲述,完全复制的代码,但是为什么会出错?
代码如下:
import urllib.request
import re
import os



def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
    page = urllib.request.urlopen(req)
    html = page.read().decode('utf-8')

    return html


def get_image(url):
    p = r'<img class="BDE_Image".*?src="[^"]*\.jpg".*?>'
    imagelist = re.findall(p, html)
    try:
      os.mkdir("NewPics")
    except FileExistsError:
      pass
    os.chdir("NewPics")
   
   
    '''
    for each in imagelist:
      print(each)
    '''
    for each in imagelist:
      filename = each.split("/")[-1]
      urllib.request.urlretrieve(each, filename, None)

      
if __name__ == '__main__':
    url = "https://tieba.baidu.com/p/6426975446"
    get_image(open_url(url))
   
   
提示以下错误:      
Traceback (most recent call last):
File "C:\Users\huahua\Desktop\python\download_p.py", line 37, in <module>
    get_image(open_url(url))
File "C:\Users\huahua\Desktop\python\download_p.py", line 18, in get_image
    imagelist = re.findall(p, html)
NameError: name 'html' is not defined

wp231957 发表于 2020-4-5 15:15:38

为什么不贴错误信息呢

zltzlt 发表于 2020-4-5 17:24:31

这样试试:

import urllib.request
import re
import os


def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent',
                   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                   '(KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
    page = urllib.request.urlopen(req)
    html = page.read().decode('utf-8')

    return html


def get_image(html):
    p = r'<img class="BDE_Image".*?src="[^"]*\.jpg".*?>'
    imagelist = re.findall(p, html)
    try:
      os.mkdir("NewPics")
    except FileExistsError:
      pass
    os.chdir("NewPics")

    for each in imagelist:
      filename = each.split("/")[-1]
      urllib.request.urlretrieve(each, filename, None)


if __name__ == '__main__':
    url = "https://tieba.baidu.com/p/6426975446"
    get_image(open_url(url))
页: [1]
查看完整版本: 写出的爬图py老是出错,请指正