首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python bs4问题

Python bs4问题
EN

Stack Overflow用户
提问于 2019-03-19 06:23:51
回答 1查看 47关注 0票数 2

我已经写了一个小的Python应用程序,但它不能像我计划的那样工作。我想让程序询问用户,他/她想要在他/她的驱动器上保存多少带有Unsplash中所选标签的图像。

代码语言:javascript
复制
res=requests.get("https://unsplash.com/search/photos" + "/" +  " ".join(sys.argv[1:]))
res.raise_for_status
soup=bs4.BeautifulSoup(res.text)
elemLinks=soup.select('img._2zEKz')
numb=int(input("How many images do you want to save?"))

在那之后,我想一个接一个地打开图像,并询问用户他/她是否想要保存这个特定的图像,直到它达到特定的数字。

代码语言:javascript
复制
numOpen=int(min(50,len(elemLinks)))
imagesSaved=0
i=0

while imagesSaved < numb and i<numOpen:
    try:
        src=elemLinks[i].get("src")
        if src==None:
            i+=1
            continue
        webbrowser.open(elemLinks[i].get("src"))
        photoUrl=elemLinks[i].get("src")
        res=requests.get(photoUrl)
        res.raise_for_status
        print ("Do you want to save it? (y/n)")
        ans=input()
        if ans=="y":
            name=input("How to name it?")
            fileName=name+".jpg"
            fileNames.append(fileName)
            imageFile=open(os.path.join("wallpapers",fileName),"wb")
            print ("Saving " + fileName + " to the hard drive")
            for chunk in res.iter_content(100000):
                imageFile.write(chunk)
                imageFile.close()
                imagesSaved += 1
                i+=1
                continue
        elif ans=="n":
            i+=1
             continue
        else:
            print("Tell me if you want to save it (y/n)")
    except requests.exceptions.ConnectionError:
        print("Connection refused by the server..")
        time.sleep(5)
        continue

但当我打开前三个图像时,循环再次打开它们(第四个图像与第一个相同,第五个图像与第二个图像相同,依此类推)。每次都会发生这种情况,不同的图像类别,不同数量的我想要保存的图像。为什么它会发生,为什么前三个总是重复?

EN

回答 1

Stack Overflow用户

发布于 2019-03-19 09:42:38

这不是bs4的问题,它完全是根据得到的html做它应该做的事情。如果您查看html (不是在DEV工具中,而是在res.text中),它的前3个元素有一个src url,然后直到第11个元素才有,这也是第一个图像。这就是html的方式,页面是动态的。

实际上,有一种更好的方法可以通过访问api获取图像。我也稍微修改了一下代码,希望能把它弄清楚一点。我也只是快速地测试了它,但希望它能让您继续:

代码语言:javascript
复制
import requests
import webbrowser
import math
import os

query=(input("What type of images would you like? "))


req_url = 'https://unsplash.com/napi/search/photos'

params = {
'query': query,
'xp': '',
'per_page': '30',
'page': '1'}

jsonObj = requests.get(req_url, params = params).json()

numb=int(input('There are %s "%s" images.\nHow many images do you want to save? ' %(jsonObj['total'], query))) 
pages = list(range(1,math.ceil(numb/30)+1))
max_allowed = 50


fileNames = []
count = 1
for page in pages:
    params = {
            'query': query,
            'xp': '',
            'per_page': '30',
            'page': page}

    jsonObj = requests.get(req_url, params = params).json()
    for item in jsonObj['results']:
        pic_url = item['urls']['raw']
        webbrowser.open(item['urls']['raw'])

        valid_ans = False
        while valid_ans == False:
            ans = input("Do you want to save it? (y/n) ")
            if ans.lower() == "y":
                name=input("How to name it? ")
                fileName=name+".jpg"
                fileNames.append(fileName)
                print ("Saving " + fileName + " to the hard drive")
                with open(os.path.join("wallpapers",fileName), 'wb') as handle:
                    response = requests.get(pic_url, stream=True)
                    if not response.ok:
                        print (response)
                    for chunk in response.iter_content(100000):
                        handle.write(chunk)                
                valid_ans = True

            elif ans.lower() == "n":
                valid_ans = True
                pass

            else:
                print ('Invalid response.')

        count += 1
        if count > numb:
            print ('Reached your desired number of %s images.' %(numb))
            break
        if count > max_allowed:
            print ('Reached maximum number of %s images allowed.' %(max_allowed))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55230954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档