Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python bs4问题_Python_Beautifulsoup - Fatal编程技术网

Python bs4问题

Python bs4问题,python,beautifulsoup,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('i

我已经编写了一个小型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
numOpen=int(最小(50,len(elemLinks)))
imagesSaved=0
i=0

虽然imagesSavedres.text
),它有一个用于前3个元素的src url,那么在第11个元素之前没有,这也是第一个图像。这就是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))

这都是一个脚本,对吗?在中间有注释吗?<代码>元素链接< /代码>包含你所期望的不同对象,而不是重复?Ya,我也看到了。问题是dev工具在呈现页面后会显示该页面
requests.get()
在呈现html源代码之前获取它。这就是为什么在使用beautifulsoup进行解析时,有时无法找到要查找的内容。当然,您可以获得所有数据,但正如我所说,您必须允许站点进行渲染。我通常用硒来做这件事。但是,除非我能找到另一种方法,例如我在这里使用的方法(或者有时数据是
标记中的json格式),否则我不会像以前那样使用Selenium。谢谢,chittown88!显然我会试试看!但我没有得到一件事——当我在Unsplash上用开发工具检查标记“cat”时,似乎每个图像都有一个src atribute,而不仅仅是其中的3个。同样,可能只是页面是动态的问题。您在开发工具中看到的不一定是beautifulsoup正在使用的,因为beatufulsoup的html源代码不是包含完整数据的呈现页面。