【问题标题】:How to put the image files I scraped using Beautiful soup into a list?如何将我使用 Beautiful soup 抓取的图像文件放入列表中?
【发布时间】:2018-07-04 18:31:50
【问题描述】:

这是我用来从 reddit 上的 r/pics 获取所有图片并将其放入目录的代码。我希望能够获取目录中的实际文件并将其放入列表中。坚持如何做到这一点。

import requests
from bs4 import BeautifulSoup as bs
import os

url = "https://www.reddit.com/r/pics/"
r = requests.get(url)
data = r.text
soup = bs(data,'lxml')

image_tags = soup.findAll('img')

if not os.path.exists('direct'):
    os.makedirs('direct')

os.chdir('direct')
x = 0

for image in image_tags:
    try:
        url = image['src']
        source = requests.get(url)
        if source.status_code == 200:
            img_path = 'direct-' + str(x) +'.jpg'
            with open(img_path, 'wb') as f:
                f.write(requests.get(url).content)
                f.close()
                x+=1
    except:
        pass

编辑:这里是更新的代码,但仍在处理问题

import requests
from bs4 import BeautifulSoup as bs
import os


url = "https://www.reddit.com/r/drawing"
r = requests.get(url)
data = r.text
soup = bs(data,'lxml')

image_tags = soup.findAll('img')

if not os.path.exists('directory'):
    os.makedirs('directory')

os.chdir('directory')
x = 0
mylist = []
for image in image_tags:
    url = image['src']
    source = requests.get(url)
    if source.status_code == 200:
        img_path = 'direct-' + str(x) +'.jpg'
        with open(img_path, 'wb') as f:
            f.write(requests.get(url).content)
            mylist.append(img_path)
            f.close()
            x += 1


print(mylist)

【问题讨论】:

    标签: python web-scraping beautifulsoup python-requests reddit


    【解决方案1】:

    在代码开头创建一个列表:

    ...
    mylist = []
    ...
    

    然后在获得每张图片后,将其添加到列表中

    ...
    img_path = 'direct-' + str(x) +'.jpg'
    mylist.append(img_path)
    ....
    

    编辑:

    我执行了您更新的代码,image_tags 返回为空 - 实际上是由

    返回的页面
    url = "https://www.reddit.com/r/drawing"
    r = requests.get(url)
    data = r.text
    

    不包含任何图像。我猜 reddit 有某种保护措施可以防止你以这种方式获取图像。

    尝试添加print(data),你会明白我的意思

    你应该使用reddit api,这样reddit就不会限制你的请求。

    【讨论】:

    • 好的,所以我将 mylist = [] 放在 for 循环之前。然后我将 img_path 附加到我的“with open(img_path, 'wb') as f:”下的 mylist。但是一旦我要求打印(mylist),我仍然会得到一个空列表:“[]”。任何想法为什么?
    • @AliHalawa 看起来不错。
    • @AliHalawa 另外,删除无用的try/except - 它隐藏了代码中的错误,当错误被消除时很难编写代码并且您不能轻易知道错误中的错误消息。
    • 好的,我删除了它,但我仍然没有收到任何错误,并且我的列表仍然是空的
    • @AliHalawa 请编辑问题并将更新后的代码添加到末尾。如果您得到空列表,则 status_code 可能不是 200,这将导致 append() 部分由于 if 而永远不会执行
    猜你喜欢
    • 1970-01-01
    • 2018-07-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 2018-05-11
    • 2023-03-31
    相关资源
    最近更新 更多