Поэтому я пытаюсь добавить каждое изображение из каждого поста Reddit, которое я извлекаю и храню в каталоге с Beautiful soup, в свой список «post_imgs». Это только часть моей программы, а не полная. Я просто не уверен, как мне это сделать, так как моя функция очистки веб-страниц и функция добавления списка разделены. Для работы моей программы эти две функции должны быть отдельными. Это для бота, над которым я работаю как личный проект.
import bs4 as bs
import requests
import praw
img_dir = 'pics'
def get_image(img_url):
if not os.path.exists(img_dir):
os.makedirs(img_dir)
url = img_url
r = requests.get(url)
data = r.text
soup = bs(data, 'lxml')
image_tags = soup.findAll('img')
os.chdir(img_dir)
x = 0
for image in image_tags:
try:
url = image['src']
source = requests.get(url)
if source.status_code == 200:
img_file = img_dir + str(x) + '.jpg'
with open(img_file, 'wb') as f:
f.write(requests.get(url).content)
f.close()
x += 1
return img_file #is this right?
except:
pass
return ''
def appending_lists(subreddit_info):
post_links = []
post_titles = []
post_ids = []
post_imgs = []
for submission in subreddit_info.new(limit=5):
if not already_tweeted(submission.id):
post_titles.append(submission.title)
post_links.append(submission.shortlink)
post_ids.append(submission.id)
post_imgs = os.listdir(get_image(submission.shortlink)) #this is where my problem is
#How do I add the image file into this list.
return post_links, post_titles, post_ids, post_imgs
Если вы не понимаете, что такое "submission.id, submission.title" и т. Д., Это просто означает, что я извлекаю, используя praw, идентификатор и заголовок сообщений Reddit.
Вот обновленная версия
def get_image(img_url):
url = img_url
r = requests.get(url)
data = r.text
soup = bs(data, 'lxml')
image_tags = soup.findAll('img')
os.chdir(img_dir)
x = 0
mylist = []
for image in image_tags:
try:
url = image['src']
source = requests.get(url, stream = True)
if source.status_code == 200:
img_file = img_dir + str(x) + '.jpg'
with open(img_file, 'wb') as f:
f.write(requests.get(url).content)
mylist.append(img_file)
f.close()
x += 1
return img_file
except:
mylist.append(None)
return mylist
def appending_lists(subreddit_info):
post_links = []
post_titles = []
post_ids = []
post_imgs = []
for submission in subreddit_info.new(limit=5):
if not already_tweeted(submission.id):
post_titles.append(submission.title)
post_links.append(submission.shortlink)
post_ids.append(submission.id)
post_imgs = get_image(submission.shortlink).copy() #this is where my problem is
#How do I add the image file into this list.
return post_links, post_titles, post_ids, post_imgs