프로젝트 이름/설명
프로젝트 생김새(레이아웃)
🤔 개발해야 하는 기능 (우선순위별 정렬)
프로젝트에 필요한 데이터 소스
이번주 목표
import urllib.request
from bs4 import BeautifulSoup
url = 'https://search.naver.com/search.naver?where=post&sm=tab_jum&query=%ED%8C%8C%EC%9D%B4%EC%8D%AC'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
titles = soup.find_all(class_='sh_blog_title')
comments = soup.find_all(class_='sh_blog_passage')
for title in titles:
print(title.attrs['title'])
print(title.attrs['href'])
for comment in comments:
print(comment.text)
🚩 네이버 검색 결과 불러오기 성공 (제목, 링크, 코멘트)
images = soup.find_all(class_='sh_blog_thumbnail')
for image in images:
print(image.attrs['src'])
🚩 이미지 불러오기 성공 (생각보다 오래 헤맸다..)
import urllib.parse #자동 변환 프로그램
baseUrl = 'https://search.naver.com/search.naver?where=post&sm=tab_jum&query='
plusUrl = (input('검색어를 입력하세요:')+'꿈해몽')
#url = baseUrl + plusUrl 검색어를 한글로 입력시 자동변환이 되지 않아 오류
url = baseUrl + urllib.parse.quote_plus(plusUrl) #자동변환
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
🚩 문제점
1) 키워드 입력시 '꿈해몽' 이라는 단어와 함께 검색 👌
2) 순서대로 print 하기
plusUrl = urllib.parse.quote_plus((input('검색어를 입력하세요: ') + '꿈해몽'))
pageNum = 1
i = input('몇개의 결과를 보여드릴까요? : ') # 10개 단위로 입력, 최대 100개
lastPage = int(i) - 9
while pageNum < lastPage + 1:
url = f'https://search.naver.com/search.naver?date_from=&date_option=0&date_to=&dup_remove=1&nso=&post_blogurl=&post_blogurl_without=&query={plusUrl}&sm=tab_pge&srchby=all&st=sim&where=post&start={pageNum}'
# f 포맷팅
pageNum += 10
titles = soup.find_all(class_='sh_blog_title')
comments = soup.find_all(class_='sh_blog_passage')
images = soup.find_all(class_='sh_blog_thumbnail')
days = soup.find_all(class_='txt_inline')
if len(titles) == len(comments) and len(comments) == len(images) and len(images) == len(days):
for i in range(len(titles)):
title = titles[i]
comment = comments[i]
image = images[i]
day = days[i]
@app.route('/dream', methods=['POST'])
def post_dream():
word_receive = request.form['word_give']
plusUrl = urllib.parse.quote_plus((word_receive) + '꿈해몽')
doc = {
'title': my_title,
'url': my_url,
'comment': my_comment,
'image': my_image,
'day': my_day
}
db.myproject.insert_one(doc)
return jsonify({'result': 'success', 'msg': '검색을 시작합니다!'})
오류. for문안에서 db저장 해야함
기존 코드의 input 제거 안함
function secondClick() {
let word = $('#firstText').val();
if (word === '') {
alert('키워드를 입력해주세요.')
return;
} else {
location.href = "http://localhost:5000/1";
}
$.ajax({
type: "POST",
url: "/dream",
data: {word_give: word},
success: function (response) {
if (response["result"] == "success") {
alert(response["msg"]);
window.location.reload();
}
}
})
}
@app.route('/dream', methods=['GET'])
def read_dream():
data = list(db.myproject.find({}, {'_id': False}))
return jsonify({'result': 'success', 'allData': data})
function showArticles() {
$.ajax({
type: "GET",
url: "/dream",
data: {},
success: function (response) {
if (response["result"] == "success") {
let totals = response['allData'];
for (let i = 0; i < totals.length; i++) {
let total = totals[i];
let title = total['title'];
let url = total['url'];
let comment = total['comment'];
let day = total['day'];
makeCard(title, url, comment, day);
}
}
}
})
}
- 이미지 관련 오류가 생겨서 별도로 추출해야겠다..
- post image 삭제
선생님 혹시 운세랑 별자리 관련 Data 어디서 크롤링 하셨을까요?ㅠㅠ