python - Python bs4 问题
问题描述
我编写了一个小型 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
但是当我打开前三张图片时,循环再次打开它们(第四张图片与第一张相同,第五张与第二张相同,依此类推)。它每次都会发生,具有不同的图像类别,我要保存的图像数量不同。为什么会发生,为什么前三个总是重复?
解决方案
这不是 bs4 的问题,它正在根据它得到的 html 做它应该做的事情。如果您查看 html(不是在开发工具中,而是在 html 中res.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))
推荐阅读
- javascript - 材质 UI 无法导入和使用 ClickAwayListener
- sql - Oracle 顶点选择列表和隐藏值
- ios - SwiftUI - 在 VStack 中对齐文本
- ruby - 验证字符串数组中的字符串(几个单词)是否与 ruby 中的另一个字符串匹配
- javascript - 在输入字段中的按键上显示自动完成列表
- assembly - 如何让 gdb 显示内存偏移量
- java - Spring Boot FlywayException:无法连接到数据库。配置url、用户和密码
- javascript - 如何阻止 js2-mode 过度缩进?
- java - 当我说从 Android Studio 的菜单中添加地点时,它有时会打开地图,有时应用程序会在未打开的情况下关闭
- c++ - 如何在 Arduino 上获取实时 GPS Sim800 模块 RTC 时间