同一函数处理不同类型的数据

问题描述 投票:1回答:1

我可能已经花了很长时间,但是我很难理解为什么会收到FileNotFoundError:[Errno 2]没有这样的文件或目录:当我唯一能看到的就是链接时。使用美丽的汤

目标:下载图像并将其放置在其他文件夹中,该文件夹可以正常工作,但某些.jpg文件除外。我尝试了不同类型的路径并剥离了文件名,但问题相同。

测试图像:

[http://img2.rtve.es/v/5437650?w=1600&preview=1573157283042.jpg#不起作用

[http://img2.rtve.es/v/5437764?w=1600&preview=1573172584190.jpg #Works完美

这里是功能:

def get_thumbnail():
'''
Download image and place in the images folder
'''
soup = BeautifulSoup(r.text, 'html.parser')

# Get thumbnail  image
for  preview in soup.findAll(itemprop="image"): 
  preview_thumb = preview['src'].split('//')[1]    

# Download image 
url = 'http://' + str(preview_thumb).strip()
path_root = Path(__file__).resolve().parents[1] 
img_dir = str(path_root) + '\\static\\images\\'


urllib.request.urlretrieve(url, img_dir + show_id() + '_' + get_title().strip()+ '.jpg')

使用的其他功能:

def show_id():
  for  image_id in soup.findAll(itemprop="image"): 
    preview_id = image_id['src'].split('/v/')[1]
    preview_id = preview_id.split('?')[0]
  return preview_id

def get_title():
  title = soup.find('title').get_text()
  return title

我能解决的问题是必须找到第一个图像的图像文件夹,但第二个图像完美。

这是我不断收到的错误,它似乎在request.py处中断enter image description here

感谢您的任何输入。

python-3.x beautifulsoup urllib
1个回答
1
投票

[图像文件名中的“特殊字符”很可能会丢掉urlretrieve()(和其中使用的open()):

>>> from urllib import urlretrieve  # Python 3: from urllib.request import urlretrieve
>>> url = "https://i.stack.imgur.com/1RUYX.png"

>>> urlretrieve(url, "test.png")  # works
('test.png', <httplib.HTTPMessage instance at 0x10b284a28>)

>>> urlretrieve(url, "/tmp/test 07/11/2019.png") # does not work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 98, in urlretrieve
    return opener.retrieve(url, filename, reporthook, data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 249, in retrieve
    tfp = open(filename, 'wb')
IOError: [Errno 2] No such file or directory: '/tmp/test 07/11/2019.png'

换句话说,用作文件名的图像标题在用作保存文件名之前必须正确地预先格式化。我只是“ slugify them”来避免所有问题。一种方法是简单地使用slugify module

slugify

例如,这就是对import os from slugify import slugify image_filename = slugify(show_id() + '_' + get_title().strip()) + '.jpg' image_path = os.path.join(img_dir, image_filename) urllib.request.urlretrieve(url, image_path) 图像名称的处理:

test 07/11/2019

另请参见:

  • >>> slugify("test 07/11/2019") 'test-07-11-2019'
© www.soinside.com 2019 - 2024. All rights reserved.