안녕하세요! 차근차근 잘 보고 있습니다. 선생님이랑 똑같이 따라하고 있는데 저는 자꾸 에러가 나서요ㅠㅠ ".logo_naver"가 없어진거 같아서 다른걸 붙여서 했는데도 오류가 나는데 뭐가 잘못된 걸까요ㅠㅠㅠㅠ 답변이 선생님이랑은 다르게 이렇게 나와서요ㅠㅠ 똑같이 따라하는데 뭐가 잘못된 건지 모르겠어요ㅠㅠ
섹션 15 (프로그래밍 방식의 인가 구현 – DB 연동) 강의에서 6:10 에 작성하신 코드 위 코드에 대해서 질문 드립니다. 저는 PageDto라는 객체를 만들고 해당 객체는 String url, Set<PageRole>으로 구성되어있고 위와 같이 코드를 작성하였습니다. 데이터를 Map에 넣고 콘솔창에 출력해보았을 때 url값이 중복이라(맵의 key값) 마지막 권한만이 Map<String, String>객체에 들어가는데 하나의 url에 여러 개의 권한을 매핑 할 때 해당 구조로 작성 하는 것이 맞는지 질문 드립니다. 만약에 Map<String, Set>구조이면 이후 커스텀 매니저에서 setMapping()의 로직이 달라지는지도 궁금합니다.
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요! 쌤 인프런, 유튜브 강의 보면서 잘 만들어 가고 있었는데 현재 코드에서 아무리 수정을 해도 css를 잘못 가져오는건지 오류가 생겨서 답답해서 질문 들고 왔습니다 현재 css 코드 찾기 좀 부탁드릴게요ㅠㅠ 안되는 항목 ✔ 연예뉴스 -> 내용을 못 가져옴 ✔ 스포츠뉴스 -> 제목, 날짜, 내용 다 못 가져옴 css를 여러개 바꿔서 넣어봐도 저는 자꾸 찾을 수 없다고 크롤링 됩니다 도와주세요,,,,,,, #네이버기사 크롤링 엑셀저장 import requests from bs4 import BeautifulSoup import time import pyautogui from openpyxl import Workbook #사용자입력 keyword = pyautogui.prompt("검색어를 입력하세요") lastpage = int(pyautogui.prompt("몇 페이지까지 크롤링 할까요?")) #엑셀 생성 wb = Workbook() #엑셀시트 생성 ws = wb.create_sheet(keyword) #열 너비 조절 ws.column_dimensions['A'].width = 60 ws.column_dimensions['B'].width = 30 ws.column_dimensions['C'].width = 60 ws.column_dimensions['D'].width = 150 #행 번호 row = 1 #페이지 번호 pageNum = 1 for i in range(1, lastpage*10, 10) : print(f"{pageNum}페이지 크롤링중입니다 =================") response = requests.get(f"https://search.naver.com/search.naver?where=news&query={keyword}&sm=tab_opt&sort=1&photo=0&field=0&pd=3&ds=2024.04.11&de=2024.15.20&news&query={keyword}&start={i}") html = response.text soup = BeautifulSoup(html, 'html.parser') articles = soup.select("div.info_group") #뉴스기사 div 10개 추출 for article in articles: links = article.select("a.info") #리스트 time.sleep(0.7) if len(links) >= 2: #링크가 2개 이상이면 url = links[1].attrs['href'] #두번째 링크의 href를 추출 response = requests.get(url, headers={'User-agent': 'Mozilla/5.0'}) html = response.text soup_sub = BeautifulSoup(html, 'html.parser') content = soup_sub.select_one("#newsct_article") if content: content_text = content.get_text(separator="\n") else: content_text = "내용을 찾을 수 없습니다." title = None date = None #만약 연예 뉴스라면 if "entertain" in response.url: title = soup_sub.select_one(".end_tit") date = soup_sub.select_one("div.article_info > span > em") content = soup.select_one("#articeBody") #만약 스포츠 뉴스라면 elif "sports" in response.url: title = soup_sub.select_one(".Main_article_title") content = soup.select_one("._article_content") else: title = soup_sub.select_one(".media_end_head_headline") date = soup_sub.select_one("span.media_end_head_info_datestamp_time._ARTICLE_DATE_TIME") #본문 내용안에 불필요한 div, p제거 divs = content.select("div") for div in divs: div.decompose() paragraphs = content.select("p") for p in paragraphs: p.decompose() print("=======제목======= \n", title.text.strip() if title else "제목을 찾을 수 없습니다.") print("=======날짜======= \n", date.text if date else "날짜를 찾을 수 없습니다.") print("=======URL======= \n", url) print("=======내용======= \n", content.text.strip() if content else "내용을 찾을 수 없습니다") # 'else' 블록에서 'date' 변수 정의는 여기서 끝나도록 수정 ws['A1'] = '제목' ws['B1'] = '날짜' ws['C1'] = 'URL' ws['D1'] = '내용' ws[f'A{row}'] = title.text.strip() if title else "제목을 찾을 수 없습니다." ws[f'B{row}'] = date.text.strip() if date else "날짜를 찾을 수 없습니다." ws[f'C{row}'] = url ws[f'D{row}'] = content_text.strip() if content else "내용을 찾을 수 없습니다." row=row+1 #마지막 페이지 여부 확인하기 next_button = soup.select_one("a.btn_next") if next_button: isLastPage = next_button.attrs.get('aria-disabled', None) if isLastPage == 'true': print("마지막 페이지 입니다.") break pageNum = pageNum+1 wb.save(f"{keyword}_4월_뉴스기사_크롤링(4)_내용까지_0411~0415(3).xlsx")
안녕하세요 선생님 대학교에서 캡스톤디자인을 수행하고 있는 학생입니다. 판결문에서 사건의 원인,판결 결과,가중·감소 처벌 요소,키워드를 추출하고 싶은데 어떤 기술을 사용해야할지 막막하여 질문올리게 되었습니다. 거대언어모델은 지양하라고 교수님께서 말씀하셨습니다..ㅜ 조언을 주신다면 감사하겠습니다.
안녕하세요 강사님! dags_python_with_ templates.py 파일에서 show_templates 함수를 아무 인자도 넣지 않고 실행을 시키는데요, dag 실행시 출력되는 키워드 인자들은 에어플로우 태스크 객체에 기본으로 입력되는 값들인가요? 정확한 원리가 궁금하여 여쭤봅니다
안녕하세요 구버전에 이어 신버전 강의도 출시해주셔서 감사합니다! 구버전 커뮤니티에 질문올렸었는데요~ 이번 강의를 봐도 해결이 되지않아서 질문 올려봅니답..! 직접 spring security 메인테이너나 컨트리뷰터들한테도 물어봤는데, 제가 제대로 질문을 못해서인지 해결을 못했는데요. 시큐리티 + formlogin + Redis를 활용해서 인증방식을 구현했습니다. 아래 코드로 인증 객체를 꺼낼때 문제가 발생합니다. @ResponseStatus(HttpStatus.OK) @GetMapping("/test") public void test() { SecurityContextHolderStrategy contextHolderStrategy = SecurityContextHolder.getContextHolderStrategy(); System.out.println(">> contextHolderStrategy : " + contextHolderStrategy); // org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy@7e1fbf12 SecurityContext context = contextHolderStrategy.getContext(); System.out.println(">> context : " + context); // SecurityContextImpl [Authentication=AnonymousAuthenticationToken Authentication authentication = context.getAuthentication(); System.out.println(">> authentication : " + authentication); // AnonymousAuthenticationToken MemberContext memberContext = (MemberContext) authentication.getPrincipal(); System.out.println(">> memberContext : " + memberContext); // ClassCastException String username = memberContext.getUsername(); System.out.println(">> username : " + username); } Redis를 사용하지 않고 tomcat에 저장할 경우 session을 통해서 인증 객체를 잘 받아오는데, >> contextHolderStrategy : org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy@54f61d2b >> context : SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=com.spring.security.config.security.service.MemberContext [Username=sejinpark@email.com, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_ADMIN]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=A220DB3D8904393F7D9831276564566A], Granted Authorities=[ROLE_ADMIN]]] >> authentication : UsernamePasswordAuthenticationToken [Principal=com.spring.security.config.security.service.MemberContext [Username=sejinpark@email.com, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_ADMIN]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=A220DB3D8904393F7D9831276564566A], Granted Authorities=[ROLE_ADMIN]] >> memberContext : com.spring.security.config.security.service.MemberContext [Username=sejinpark@email.com, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_ADMIN]] >> username : sejinpark@email.com Redis만 사용하면 인증 완료 후 인증 후 요청에서 Anonymous로 변경됩니다. >> contextHolderStrategy : org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy@577154a7 >> context : SecurityContextImpl [Authentication=AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=16bec162-3ad3-459d-8b97-bf3d6f1de226], Granted Authorities=[ROLE_ANONYMOUS]]] >> authentication : AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=16bec162-3ad3-459d-8b97-bf3d6f1de226], Granted Authorities=[ROLE_ANONYMOUS]] 2024-04-17T07:49:13.061+09:00 ERROR 84540 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.ClassCastException: class java.lang.String cannot be cast to class com.spring.security.config.security.service.MemberContext (java.lang.String is in module java.base of loader 'bootstrap'; com.spring.security.config.security.service.MemberContext is in unnamed module of loader 'app')] with root cause java.lang.ClassCastException: class java.lang.String cannot be cast to class com.spring.security.config.security.service.MemberContext (java.lang.String is in module java.base of loader 'bootstrap'; com.spring.security.config.security.service.MemberContext is in unnamed module of loader 'app') at com.spring.security.controller.MemberController.test(MemberController.java:43) ~[main/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] Redis 내부에 인증객체가 저장되어 있는것 까지 확인했는데요. 혹시 SecurityFilterChain에 Redis관련 저장소를 별도로 설정을 해줘야 하는지, 어떤 부분을 확인해야하는지 여쭙고 싶습니다. Redis를 사용하는데 계속 HttpSessionSecurityContextRepository에서 시큐리티 컨텍스트를 찾을 수 없다고 나옵니답. 2024-04-17T17:05:01.251+09:00 WARN 30066 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '{authentication={authorities=[{authority=ROLE_ADMIN}], details={remoteAddress=0:0:0:0:0:0:0:1, sessionId=null}, authenticated=true, principal={password=null, username=sejinpark@email.com, authorities=[{authority=ROLE_ADMIN}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}, credentials=null, name=sejinpark@email.com}}'; are you improperly modifying the HttpSession directly (you should always use SecurityContextHolder) or using the HttpSession attribute reserved for this class? 우선 테스트용으로 SecurityFilterChain에서 아래처럼 기존 버전 처럼 사용해서 인증 상태를 무조건 저장할 수 있도록 해놨습니다. 커스텀 인증필터를 사용 안하고, SecurityContextPersistanceFilter를 사용하도록했습니다. securityContext.requireExplicitSave(false); 테스트용으로 만든 레포지토리 링크 첨부합니다! https://github.com/codesejin/security-test
안녕하세요 선생님, 질문이 있습니다. [ 기본 인증 필터 - BasicAuthenticationFilter ] - 14:00 ~ 14:20 부분에서 Http Request Header 에 Authroization Header 가 자동으로 세팅이 되는데, 이건 브라우저가 지원해주는 기능인 건가요??
타임 리프로 페이지를 구성한다면 CSRF 토큰을 타임리프에서 자동으로 생성하기 때문에 직전 세션인 [실전 프로젝트 - 회원 인증 시스템] 강의 내용으로 스프링 시큐리티 설정이 충분하지만, 타임 리프가 아닌 자바스크립트 기반의 뷰나 리액트 등으로 페이지를 구성할 때에는 [실전 프로젝트 - 비동기 인증] 으로 스프링 시큐리티를 설정해야 되는 것으로 생각하면 될까요? 그 이유는 CSRF 토큰을 자바스크립트에서는 자동으로 생성하지 않기 때문이다. 라고 이해했는데 다른 이유가 혹시 더 있을까요?
안녕하세요 네이버 메일 자동화 코드를 실행하면 메일 쓰기 버튼을 계속 찾지 못하고 있어 어떻게 수정하면 될지 문의드립니다. 메일함 이동까지는 정상적으로 되고 있으나 메일 쓰기 버튼만 찾지 못하고 있습니다. 코드는 다음과 같습니다. from selenium.webdriver import ChromeOptions from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By import time import pyperclip import pyautogui from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = ChromeOptions() options.add_experimental_option("detach", True) driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options) driver.get('https://nid.naver.com/nidlogin.login?mode=form&url=https://www.naver.com/') driver.maximize_window() # 화면 최대화 # 아이디 입력창 id = driver.find_element(By.CSS_SELECTOR, '#id') id.click() pyperclip.copy('eooe5173') pyautogui.hotkey('ctrl', 'v') time.sleep(2) # 비밀번호 입력창 passward = driver.find_element(By.CSS_SELECTOR, '#pw') passward.click() pyperclip.copy('ssw471395~') pyautogui.hotkey('ctrl', 'v') time.sleep(2) # 로그인 버튼 driver.find_element(By.CSS_SELECTOR, '#log\.login').click() time.sleep(5) # 메일함으로 이동 mailbox = driver.find_element(By.CSS_SELECTOR,'#shortcutArea > ul > li:nth-child(1) > a').click() time.sleep(5) # 내게 쓰기 버튼 writeme_button =driver.find_element(By.CSS_SELECTOR, '#root > div > nav > div > div.lnb_header > div.lnb_task > a.item.button_write').click() # 메일 제목 입력창 및 입력 mailname = driver.find_element(By.CSS_SELECTOR, '#subject_title').click() pyperclip.copy('안녕하세요') pyautogui.hotkey('ctrl', 'v') time.sleep(5) # 메일 내용 입력창 및 입력 mailinfo = driver.find_element(By.CSS_SELECTOR, '#body > div > div.workseditor-content').click() pyperclip.copy('네이버 메일 자동화입니다.') pyautogui.hotkey('ctrl', 'v') time.sleep(5) # 메일 저장 mailsave = driver.find_element(By.CSS_SELECTOR, '#content > div.mail_toolbar.type_write > div:nth-child(1) > div > button.button_write_task').click() time.sleep(5) 에러는 동일하게 다음과 같이 노출되고 있습니다. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#root > div > nav > div > div.lnb_header > div.lnb_task > a.item.button_write"} (Session info: chrome=123.0.6312.123) Stacktrace: GetHandleVerifier [0x00D14CA3+225091] (No symbol) [0x00C44DF1] (No symbol) [0x00AE9A7A] (No symbol) [0x00B2175B] (No symbol) [0x00B2188B] (No symbol) [0x00B57882] (No symbol) [0x00B3F5A4] (No symbol) [0x00B55CB0] (No symbol) [0x00B3F2F6] (No symbol) [0x00B179B9] (No symbol) [0x00B1879D] sqlite3_dbdata_init [0x01189A43+4064547] sqlite3_dbdata_init [0x0119104A+4094762] sqlite3_dbdata_init [0x0118B948+4072488] sqlite3_dbdata_init [0x00E8C9A9+930953] (No symbol) [0x00C507C4] (No symbol) [0x00C4ACE8] (No symbol) [0x00C4AE11] (No symbol) [0x00C3CA80] BaseThreadInitThunk [0x764EFCC9+25] RtlGetAppContainerNamedObjectPath [0x77DE7C5E+286] RtlGetAppContainerNamedObjectPath [0x77DE7C2E+238]
spring boot 로 프로젝트 만들고 하는중이라서 부트에서 테스트 하고 있는데요. 구글링 해서 테스트 세팅하고 modelAndView 까지 했는데 view 값은 가져오는데 model 값이 안가져와지네요.... @MockBean 으로 Service 를 bean 등록 시키고 Service 에서 getList 할때 뭔가 잘안되는거 같은데 혹시 어떤게 잘못됬는지 확인 가능하신가요 ?? Controller Service test Controller test Constroller test 결과