N
N
NitroDesktop2021-06-02 23:04:11
Python
NitroDesktop, 2021-06-02 23:04:11

Image download not working, can it be fixed?

What is the problem?


Traceback (most recent call last):
File "d:\Documents\test\Py\news\downloadimg.py", line 29, in
f.write(r.content)
TypeError: write() argument must be str, not bytes


import requests  
from lxml import html  
import sys,os
# import urlparse
import urllib.parse

urs_adr=input()

response = requests.get(urs_adr)  
parsed_body = html.fromstring(response.text)

# Парсим ссылки с картинками
images = parsed_body.xpath('//img/@src')  
if not images:  
    sys.exit("Found No Images")

t_folder="downloaded_images"

# Конвертирование всех относительных ссылок в абсолютные
images = [urllib.parse.urljoin(response.url, url) for url in images]  
print('Found %s images' % len(images))
if not os.path.exists(t_folder):
    os.mkdir(t_folder)
# Скачиваем только первые 10
for url in images[0:10]: 
    r = requests.get(url)
    
    f = open('downloaded_images/%s' % url.split('/')[-1], 'w')
    f.write(r.content)
    f.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-06-02
@SoreMix

Open the file to write bytes in the mode wb
Where w- write, and b- respectively, bytes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question