728x90
반응형
팔로우 언팔로우 기능 프론트의 버튼에 연동시키기
- 발생 에러 : await' expressions are only allowed within async functions and at the top levels of modules
- 발생 이유 : function 정의할 때 함수 앞에 async 작성 안 함
- 해결 : async 작성함
- 알게된 것
- await은 async로 정의된 함수 안에서만 쓰일 수 있다.
- 수업 때 fetch 사용시 async await을 써서 마냥 그렇게 써야 되는 줄 알았는데, 그냥 fetch만 단독으로 써도 됐고, 그 결과물을 굳이 항상 변수에 담아 줄 필요도 없었다. 그래서 팔로우 언팔로우 기능의 경우 따로 변수 설정 없이 구현했다.
- appendChild로 실질적인 버튼 생성 시 fetch가 먼저 되고 나서 그 다음에 버튼을 생성해 줘야 한다.
const id = person.id
fetch(`http://127.0.0.1:8000/users/follow/${id}/`, {
headers: {
"authorization": "Bearer " + localStorage.getItem("access")
},
method: 'POST',
body: {}
})
alert("언팔로우!")
window.location.reload()
}
wrappingDiv.appendChild(unfollow)
})
기타
- 자바스크립트에서 태그에 속성 추가하기 → 객체.속성명 = 값
const id = person.id
fetch(`http://127.0.0.1:8000/users/follow/${id}/`, {
headers: {
"authorization": "Bearer " + localStorage.getItem("access")
},
method: 'POST',
body: {}
})
alert("언팔로우!")
window.location.reload()
}
wrappingDiv.appendChild(unfollow)
})
- html 띄우며 페이지 이동→ location.herf는 이미 알고 있었는데 flask에서 app.py의 라우터로 이동하던 거밖에 생각이 안 나서 이게 여기서 등장할 줄 상상도 못했다. 자바스크립트무지렁이…. 지금 이 날 til 쓴다고 메모해둔 거 프젝 끝나고 메모 보면서 쓰는 거라 아는데, 미래의 금빈이는 주소창에 ~~html이라고 뜨는 걸 해결하기 위해 이틀을 골머리를 앓다가 일단 이 상태로 진행하라는 말에 스트레스 받아서 울었다^^ 주소 하나 못 바꾸는 바보… 지금 아는 지식으로 어떻게든 해결해보려 한 고집쟁이……(구글링 안 한 건 아님)
- window.location.href = “<html 파일명>.html”
내가 작성항 크롤링 코드
- 누군가에겐 별 거 아닌 코드일지 모르지만, 다 이렇게 시작하는 거지 뭐. 열심히 구글링 해보면서 페이지 이동도 시켜보고 좋았다. 브라우저 안 켜지게 하는 option도 신기했고. 음음. movie_id는 팀원 분께서 따로 생성해 달라고 해서 나중에 추가했다. movie_id 뽑으려고 원래 안 썼던 enumerate를 추가적으로 사용했다.
from selenium import webdriver
from bs4 import BeautifulSoup
import time
from selenium.common.exceptions import NoSuchElementException
from pymongo import MongoClient
import requests
# JSON
import json
# 크롬 드라이버 세팅용
from webdriver_manager.chrome import ChromeDriverManager
# headless 옵션용
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
# ↑ 셀레니움이 크롬 드라이브를 잡아서 네이버 영화 페이지 오픈
url = "https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=cnt&date=20221101"
driver.get(url)
time.sleep(1)
# ↑ 그리고 1초 정도 기다려서 페이지가 다 로드되고 나면
# ↓ 거기에 있는 HTML 소스를 다 가져온다.
req = driver.page_source
soup = BeautifulSoup(req, 'html.parser')
# 가져온 소스를 BeautifulSoup에 넣어서 분석할 준비
movies = soup.select('#old_content > table > tbody > tr')
movie_list=[]
http = 'https://movie.naver.com/'
for k, movie in enumerate(movies):
title = movie.select_one('td.title > div > a')
if title is not None:
href = http+title['href']
driver.execute_script(f"window.open('{href}');")
driver.switch_to._driver.window_handles[1]
driver.get(href)
time.sleep(1)
# ↑ 그리고 1초 정도 기다려서 페이지가 다 로드되고 나면
# ↓ 거기에 있는 HTML 소스를 다 가져온다.
req = driver.page_source
soup = BeautifulSoup(req, 'html.parser')
# 가져온 소스를 BeautifulSoup에 넣어서 분석할 준비
poster = soup.select_one('#content > div.article > div.mv_info_area > div.poster > a > img')["src"]
description = soup.select_one('#content > div.article > div.section_group.section_group_frst > div:nth-child(1) > div > div.story_area > p.con_tx')
title = title.text
new_data = {"model":"movies.movie"}
new_data["fields"] = {}
new_data["fields"]["movie_id"] = k
new_data["fields"]["title"] = title
new_data["fields"]["description"] = description
new_data["fields"]["poster"] = poster
movie_list.append(new_data)
driver.quit()
# from pprint import pprint
# pprint(movie_list)
with open('movie_movie.json','w',encoding='UTF-8') as f :
json.dump(movie_list, f,default=str, ensure_ascii=False, indent=2)반응형
'Programming > TIL and WIL' 카테고리의 다른 글
| 💖 221106 Today I Learned 💖 (0) | 2022.11.09 |
|---|---|
| 💖 221105 Today I Learned 💖 (0) | 2022.11.09 |
| 💖221103 Today I Learned💖 (0) | 2022.11.04 |
| 💖221102 Today I Learned💖 (0) | 2022.11.04 |
| 💖Weekly I Learned💖 (0) | 2022.10.31 |