我试图在谷歌上找到无版权的图片,但我无法获得正确的图片URL。我的代码应用了正确的过滤器并将我引导到正确的页面,但是它检索没有版权免费和大小过滤器的图像的URL,我不确定为什么。先谢谢你
import requests
import urllib.request
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
url = 'https://google.com/search?q='
input = 'cat'
#string: tbm=isch --> means image search
#tbs=isz:m --> size medium
#il:cl --> copy right free(i think)
url = url+input+'&tbm=isch&tbs=isz:m%2Cil:cl'
print(url)
html = urlopen(Request(url, headers={'User-Agent': 'Google Chrome'}))
'''with urllib.request.urlopen(url) as response:
html = response.read()
print(html)'''
#print(str(r.content))
soup = BeautifulSoup(html.read(),'html.parser')
#using soup to find all img tags
results = soup.find_all('img')
str_result = str(results)
lst_result = str_result.split(',')
#trying to get the first link for the images with the appropriate settings
link = lst_result[4].split(' ')[4].split('"')[1]
# writing into the appropriate testing file, to be changed
file = open('.img1.png','wb')
get_img = requests.get(link)
file.write(get_img.content)
file.close()
您可以尝试使用更简单的方法,而不必指定
tbs=il:cl
参数,也不必通过搜索“pexelscat”或“unsplashcat”来玩猜谜游戏,这些图像肯定是在CreativeCommons下许可的或者,您可以尝试在查询的开头添加一个过滤器参数(
tbs=il:cl
)加上pexels/unsplash这些图片在默认情况下是完全免费的,因为这些网站是为商业或非商业用途提供免费图片而设计的,谷歌将只显示这些网站的结果
要查找和提取原始图像URL,您需要通过
regex
从<script>
标记解析它首先,您需要使用
bs4
查找所有脚本标记:其次,要使用
regex
匹配所需的模式:第三,迭代匹配,逐个提取和解码每个URL:
代码和full example in the online IDE that scrapes more:
或者,您可以使用SerpApi中的Google Images API跳过此过程。这是一个免费的付费API
主要区别在于,您只需要迭代结构化JSON,因为其他一切都已经为最终用户完成了
要集成的代码:
顺便说一句,我写了一篇关于刮削的博客文章,其中用视觉表现更深入地介绍了它
相关问题 更多 >
编程相关推荐