为什么这个python代码没有刮掉任何东西?

时间:2018-02-27 15:01:24

标签: python python-3.x

我正试图根据bing的搜索结果来搜索图像。但它不起作用。这是我的代码: -

import requests
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO

v = 0
s = input("Search: ")
p = {"q": s}
r = requests.get("https://www.bing.com/images/search", params=p)
print(r.status_code)
soup = BeautifulSoup(r.text, "html.parser")
items = soup.findAll("a", {"class": "iusc"})

for item in items:
    img_obj = requests.get(item.attrs["href"])
    img = Image.open(BytesIO(img_obj.content))
    img.save("./images/"+v,img.format)
    v += 1

1 个答案:

答案 0 :(得分:0)

使用以下代码更改您的代码:

items = soup.find_all("a", {"class": "thumb"})
for item in items:
    img_obj = requests.get(item["href"])
    if img_obj.ok:
        img = Image.open(BytesIO(img_obj.content))
        img.save("./images/" + str(v) + '.' + img.format, img.format)
        v += 1
    else:
        print(img_obj.status_code)

您的代码中存在一些问题