一、背景
要做一个背单词的,用表情包来显示单词的意思比较带劲,所以做了一个,搜狗的引擎加密太厉害,就使用来搜狗的图片搜索,自己看情况根据也可以换。
二、代码
import requests
import json
import os
def face_image ( name, num) :
'''
name:表情包的关键字
num:下载的数目(0-20)
'''
for i in os. listdir( ) :
if i[ : - 4 ] in [ str ( i) for i in range ( num) ] :
os. remove( i)
url= 'https://pic.sogou.com/pics/json.jsp'
data = { 'query' : '%s 表情' % name}
headers = { "User-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0" ,
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" ,
"Accept-Language" : "en-US,en;q=0.5" ,
"Accept-Encoding" : "gzip, deflate" ,
"Connection" : "keep-alive" ,
"Content-Type" : "application/x-www-form-urlencoded" ,
}
resp = requests. get( url, headers= headers, params= data)
for i in range ( num) :
end= ''
res= json. loads( resp. content. decode( 'gb18030' ) ) [ 'items' ] [ i] [ 'picUrl' ]
if res[ - 4 : ] == '.jpg' or res[ - 4 : ] == '.png' or res[ - 4 : ] == '.gif' :
end= res[ - 4 : ]
elif data[ : 2 ] == b'\xff\xd8' :
end= '.jpg'
elif data[ : 8 ] == b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' :
end= '.png'
elif data[ : 3 ] == b'GIF' :
end= '.gif'
data= requests. get( res, headers= headers) . content
with open ( str ( i) + end, 'wb' ) as f:
f. write( data)
face_image( '垃圾分类' , 5 )