简体   繁体   English

python-未定义NameError全局名称'buf'

[英]python - NameError global name 'buf' is not defined

I don't know what this error means. 我不知道这个错误是什么意思。 Any advice about the error or the rest of the code is greatly appreciated. 非常感谢您提供有关错误或代码其余部分的任何建议。

import urllib
import urllib2
import os
import re
from bs4 import BeautifulSoup
def image_scrape():
    url = raw_input("Type url for image scrape: ")
    content = urllib2.urlopen(url).read()
    soup = BeautifulSoup(content)
    name = 0
    for tag in soup.find_all(re.compile("img")):
        path = 'C:\Users\Sorcerer\Downloads'
        name += 1
        filename = name
        file_path = "%s%s" % (path, filename)
        downloaded_image = file(file_path, "wb")
        downloaded_image.write(buf)
        downloaded_image.close()

image_scrape()

You have a line in your code: 您的代码中有一行:

downloaded_image.write(buf)

The Python interpreter has not seen this variable buf before in your code. Python解释器在您的代码中之前没有看到此变量buf And hence the error. 因此,错误。

Thoughts on the rest of your code: 关于其余代码的想法:

  • It is advisable to use the os module to do what you are doing with this line: 建议使用os模块执行以下操作:

     file_path = "%s%s" % (path, filename) 

    like this: 像这样:

     import os path = os.path.normpath('C:\\\\Users\\\\Sorcerer\\\\Downloads') file_path = os.path.join(path, name) 
  • Looks like you are trying to find all the image links in the page and trying to save it to the file system at the location referenced by file_path . 似乎您正在尝试查找页面中的所有图像链接,并尝试将其保存到file_path引用的位置的文件系统中。 Assuming the link to the image is in the variable tag , this is what you do: 假设到图像的链接在变量tag ,这是您要做的:

     import requests r = requests.get(tag, stream=True) if r.status_code == 200: with open(name, 'wb') as f: for chunk in r.iter_content(): f.write(chunk) f.close() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM