사진검색
원하는 키워드를 입력하면 사진을 보내주는 기능을 만들어봤습니다.
!이미지 원하는키워드 를 입력하면 키워드를 네이버에 검색하여 이미지를 가져옵니다.
import urllib
from urllib.request import Request
import bs4
3가지를 임포트 하였습니다.
먼저 실행영상입니다.
아래는 전체 코드입니다.
if message.content.startswith('!이미지'):
Text = ""
learn = message.content.split(" ")
vrsize = len(learn) # 배열크기
vrsize = int(vrsize)
for i in range(1, vrsize): # 띄어쓰기 한 텍스트들 인식함
Text = Text + " " + learn[i]
print(Text.strip()) # 입력한 명령어
randomNum = random.randrange(0, 40) # 랜덤 이미지 숫자
location = Text
enc_location = urllib.parse.quote(location) # 한글을 url에 사용하게끔 형식을 바꿔줍니다. 그냥 한글로 쓰면 실행이 안됩니다.
hdr = {'User-Agent': 'Mozilla/5.0'}
# 크롤링 하는데 있어서 가끔씩 안되는 사이트가 있습니다.
# 그 이유는 사이트가 접속하는 상대를 봇으로 인식하였기 때문인데
# 이 코드는 자신이 봇이 아닌것을 증명하여 사이트에 접속이 가능해집니다!
url = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query=' + enc_location # 이미지 검색링크+검색할 키워드
print(url)
req = Request(url, headers=hdr)
html = urllib.request.urlopen(req)
bsObj = bs4.BeautifulSoup(html, "html.parser") # 전체 html 코드를 가져옵니다.
# print(bsObj)
imgfind1 = bsObj.find('div', {'class': 'photo_grid _box'}) # bsjObj에서 div class : photo_grid_box 의 코드를 가져옵니다.
# print(imgfind1)
imgfind2 = imgfind1.findAll('a', {'class': 'thumb _thumb'}) # imgfind1 에서 모든 a태그 코드를 가져옵니다.
imgfind3 = imgfind2[randomNum] # 0이면 1번째사진 1이면 2번째사진 형식으로 하나의 사진 코드만 가져옵니다.
imgfind4 = imgfind3.find('img') # imgfind3 에서 img코드만 가져옵니다.
imgsrc = imgfind4.get('data-source') # imgfind4 에서 data-source(사진링크) 의 값만 가져옵니다.
print(imgsrc)
embed = discord.Embed(
colour=discord.Colour.green()
)
embed.set_image(url=imgsrc) # 이미지의 링크를 지정해 이미지를 설정합니다.
await client.send_message(message.channel, embed=embed) # 메시지를 보냅니다.
주석에 설명 적어놨습니다!
아래는 전체소스코드 깃허브 주소입니다.
https://github.com/YeChan39/YeChanParkDark
아래는 네이버블로그 포스팅 주소입니다.
https://blog.naver.com/turnbf/221424602771
'디스코드 봇 개발일지' 카테고리의 다른 글
| 디스코드 봇 개발일지#19 (2) | 2019.02.07 |
|---|---|
| 디스코드 자작봇 개발일지#18 (0) | 2018.12.23 |
| 디스코드 자작봇 개발일지#16 (0) | 2018.12.21 |
| 디스코드 봇 개발일지#15 (0) | 2018.12.20 |
| 디스코드 자작봇 개발일지#14 (0) | 2018.10.30 |