파이썬

옥션 검색어를 통한 DB화 시키기...

귀신이보인다 2022. 1. 8. 23:58
728x90
반응형

심심하여 만들어보았으며 중복 DB를 하지 않을거 같습니다만 테스트를 완료하지 않았습니다.

현재는 검색어를 입력하여 검색에 따라 해당 쇼핑몰의 상품을 검색하여 해당 상품의 링크와 상품명 가격을 DB에 저장만 합니다.

이를 좀더 변경하여 최저가나 혹은 기타 다른 목적으로 활용해보려고 만든것이고 해당 소스를 통해 이용하실분들은 이용하셔도 됩니다.

import requests, sys
from bs4 import BeautifulSoup as bs
try:
	import sqlite3
except ImportError:
	os.system('pip install sqlite3')
	import sqlite3	
	
def add(item_url, item_name, item_price):
	try:
		con = sqlite3.connect('./auction.db',timeout=60)
		cur = con.cursor()
		sql = "select * from auction where item_name = ?"
		cur.execute(sql, (item_name,))
		row = cur.fetchone()
		if row != None:
			pass
		else:
			cur.execute("INSERT OR REPLACE INTO auction (item_url, item_name, item_price) VALUES (?, ?, ?)", (item_url, item_name, item_price))
			con.commit()
			print('{} {}'.format(item_name, item_price))
	except:
		con.rollback()
	finally:		
		con.close()
		
def main():
	conn = sqlite3.connect('./auction.db',timeout=60)
	conn.execute('CREATE TABLE IF NOT EXISTS auction (item_url TEXT, item_name TEXT, item_price TEXT)')
	conn.close()
	n = input('검색어 (q 를 입력하면 종료합니다.): ')
	if n == "q":
		print("종료합니다.")
		sys.exit()
	else:
		header = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)\AppleWebKit 537.36 (KHTML, like Gecko) Chrome","Accept":"text/html,application/xhtml+xml,application/xml;\q=0.9,imgwebp,*/*;q=0.8"}
		with requests.Session() as s:
			page = 1
			while True:
				url2 = 'http://browse.auction.co.kr/search?keyword=' + n + '&p=' + str(page)
				req = s.get(url2)
				html = req.text
				gogo = bs(html, "html.parser")	
				test = gogo.findAll("div",{"class":"section--itemcard_info_major"})
                test1 = gogo.find("div",{"class":"section--itemcard_info_major"})
				if test1 == None:
                	print("검색된 페이지가 없습니다.")
					break
				else:
					for i in test:
						item_url = i.find("a",{"class":"link--itemcard"})['href']
						item_name = i.find("span",{"class":"text--title"}).text
						item_price = i.find("strong",{"class":"text--price_seller"}).text
						add(item_url, item_name, item_price)
				page += 1
if __name__ == "__main__":
	main()

테스트를 하지 않았습니다.

여기서 수정할곳을 마음대로 변경하셔서 사용하실분들은 사용하세요 ㅎㅎㅎ

728x90
반응형