Python bs4问题

时间:2019-03-18 22:23:51

标签: python beautifulsoup

我已经编写了一个小型Python应用程序,但是按我的计划无法正常工作。 我想让程序询问一个用户,他/她希望从Unsplash中选择多少个带有所选标签的图像保存在他/她的驱动器上。

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?"))

之后,我要一个接一个地打开图像,并询问用户是否要保存此特定图像,直到达到特定数量为止。

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

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

1 个答案:

答案 0 :(得分:0)

bs4没问题,它正在根据所获取的html进行应有的操作。如果您查看html(不在开发工具中,而是res.text),则它的前3个具有src url,然后直到第11个元素(第一个图像)才显示None。这就是html的方式,页面是动态的。

实际上,有一种更好的方法可以通过访问api获取图像。我也对代码进行了一些更改,以期希望将其清除。我也只是对其进行了快速测试,但是希望它可以帮助您:

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))