Skip to content

Instantly share code, notes, and snippets.

@pokev25
Last active June 7, 2019 06:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pokev25/4c4031a1a0bfb66cd7821ee6f57041fd to your computer and use it in GitHub Desktop.
Save pokev25/4c4031a1a0bfb66cd7821ee6f57041fd to your computer and use it in GitHub Desktop.
텔레그램 봇으로 알라딘 중고매장 검색 결과 전달 받기
# -*- coding: utf-8 -*-
import sys
import re
import mechanize
import urllib2
import cookielib
from bs4 import BeautifulSoup
import telepot
# telepot 로 텔레그램 메시지 준비
YOUR_ACCESS_TOKEN = "" # 여기에 자신의 토큰을 넣으시면 됩니다
mytelegramid=0
bot = telepot.Bot(YOUR_ACCESS_TOKEN)
# 파일에서 서점 책 데이터 읽기
AladinBook = []
AladinShop = []
f1 = open("OffAladin.ini")
idx = 0
tmp = ""
for s in f1:
if idx == 0:
idx += 1
AladinShop = s.split(",")
elif idx % 2 == 1:
tmp = s.replace("\n", "").decode('utf-8')
idx += 1
elif idx % 2 == 0:
AladinBook.append((tmp, s.replace("\n", "")))
idx += 1
# 디버그를 위해 데이터를 한번 뿌려주지만 삭제해도 됩니다
print "Shop is "
for i in range(len(AladinShop)):
AladinShop[i] = AladinShop[i].replace(" ", "").replace("\n", "")
print AladinShop[i].decode('utf-8')
print "Book is "
for i in range(len(AladinBook)):
print AladinBook[i][0]
print "Browsing Starting "+AladinBook[i][1]
# mechanize 로 브라우저에 접속
cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_cookiejar(cj)
br.set_handle_robots(False)
for i in range(len(AladinBook)):
weburl = ("http://www.aladin.co.kr/search/wsearchresult.aspx?SearchTarget=UsedStore&SearchWord=" + AladinBook[i][1] + "&x=0&y=0")
br.open(weburl)
mobileurl = "http://www.aladin.co.kr/m/msearch.aspx?SearchTarget=UsedStore&SearchWord=" + AladinBook[i][0].replace(" ","+")
print "web url : %d "%i +weburl
soup = BeautifulSoup(br.response().read(),"html5lib")
#soup = BeautifulSoup(br.response().read())
#print soup
# <b class="bo3"> 책 제목
# <div class="ss_book_list"><ul>
# <div class="usedshop_off_text2_box">
# bcols = soup.findAll( 'b', attrs={ 'class' : "bo3" } )
cols = soup.findAll('a', attrs={'class': "usedshop_off_text3"})
#print AladinBook[i][0]
for col in cols:
#print col.text
for shop in AladinShop:
if col.text.find(shop.decode("utf-8")) >= 0:
print "telegram send message : " + col.text + u"에 " + AladinBook[i][0] + u" 입고 되었습니다 " + weburl
bot.sendMessage( mytelegramid, col.text + u"에 " + AladinBook[i][0] + u" 입고 되었습니다 "+ mobileurl)
#send message
#Bot
#bot.sendMessage(2360, " 입고 되었습니다")
#http://www.aladin.co.kr/shop/wproduct.aspx?ItemId=2227082
@pokev25
Copy link
Author

pokev25 commented Jan 31, 2017

http://m.clien.net/cs3/board?bo_style=view&bo_table=lecture&page=1&wr_id=347128

mechanizer란 걸 사용하면 간단하게 접속할 수 있고, 그 결과를 beutifulsoup로 파싱하면 간단하게 처리할 수 있습니다.
저도 이 게시판이었나 아니면 다른 블로그에서 보고 사용해봤는데 무척 간단하더군요.
먼저 결과 파일을 우클릭해서 페이지 소스 보기로 내용을 봅니다. 이 경우에는

<div class="ss_book_list">책 리스트
        <b class="bo3"> 책 제목
<div class="usedshop_off_text2_box"> 상점 리스트
        <a href="..." clase = "usedshop_off_text3"> 상점 이름

이 정도가 중요합니다. 사실 모든 div나 a, p 이런데에 class나 id가 있는 건 아니기 때문에, 떄로는 가져올 자료를 찾기 위해
몇번째 b를 읽는다... 이런 방법을 써야 할 때도 있지만, 이 사이트는 깔끔하게 class를 정해주면 되네요.

아래 소스에는 책 제목이 유니크한 경우만 고려하고 있는데, 예제 파일에 있는 호랑이의 경우, 같은 키워드가 들어간 책 제목이
무척 많습니다. 이런 경우 td들을 (table 구조체) 찾은 다음에 그 하위 항목 중에 b를 제목으로, a를 상점 이름으로 표현해야 하는데
이렇게 되면 책 한 종류만 노린다는 취지에 맞지 않기에 일단 뒀습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment