안녕하세요 강사님. 모든 강의를 수강한 이후에 왜 처음에 beautiful soup로 시작해서 selenium으로 끝이 나는지 절실하게 깨달을 수 있었습니다. 가르쳐 주신 예제를 바탕으로 개인적으로 추가 실습을 진행하면서 크롤링에 대한 이해를 높이려고 하는데 selenium의 경우 특정 버튼을 클릭하여 넘어간 이후에 크롤링이 진행되도록 자동화에 맞추어져 있는 라이브러리임을 알 수 있었습니다. 네이버 예제 화면에 있는 메일, 카페, 블로그, 쇼핑, 뉴스, 증권, 부동산, 지도, 웹툰이 모여져 있는 배너에서 사용자가 특정 버튼을 눌렀을 때 이동한 해당 페이지에서 크롤링을 진행할 수 있도록 자동화하는 예제를 스스로 만들어 공부 중인데 이러한 경우에서 if 메일 if 카페 if 블로그 같은 분기를 바탕으로 작성한 로직 대신 동적으로 사용자가 클릭했을 때의 정보를 가져올 수 있도록 하는 방법이 있을까요? 수많은 버튼이 존재하게 된다면 사용자가 어떤 버튼을 누를지 xpath라던가 class를 특정할 수 없는 경우가 생길 수 있을 것 같아서 질문 드립니다..!
안녕하세요 강사님. 질문이 있어서 남기게 되었습니다. 첫 번째 질문: 네이버 view탭 검색 결과 크롤링 2를 완료한 이후 아래 코드 실행 후 손흥민을 검색했는데 검색결과가 30개가 아닌 7개가 출력되었습니다. 이러한 이슈 때문인지 네이버 view탭 검색 결과 크롤링 3 강의가 정상적으로 진행되지 않습니다. import requests from bs4 import BeautifulSoup # beautiful soup 라이브러리 import base_url = "https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=" keyword = input("검색어를 입력하세요 : ") url = base_url + keyword print(url) headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36" } # dictionary req = requests.get(url, headers = headers) # GET 방식으로 naver에 요청 html = req.text # 요청을 하여 html을 받아옴 soup = BeautifulSoup(html, "html.parser") # html을 html.parser로 분석(클래스를 통한 객체 생성) total_area = soup.select(".total_area") timeline_area = soup.select(".timeline_area") if total_area: areas = total_area elif timeline_area: areas = timeline_area else: print("class 확인 요망") for area in areas: title = area.select_one(".api_txt_lines.total_tit") name = area.select_one(".sub_txt.sub_name") print(name.text) print(title.text) print(title["href"]) print() print(len(areas)) 두 번째 질문: 네이버 view탭 검색 결과 크롤링 3을 진행하면서 아래 코드처럼 작성하고 손흥민을 검색했을 때 NoneType 오류가 발생합니다. 첫 번째 질문의 이슈로 인해 그런 것인가요? .total_wrap.api_ani_send 클래스가 브라우저 상에서는 30개가 잘 나오는데 제대로 안 받아와진 것 같은 느낌이 듭니다. 도와주시면 감사하겠습니다 ㅠㅠ Traceback (most recent call last): File "C:\python_web_crawling\01_4_naver.py", line 30, in <module> print(title.text) ^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'text' 아래는 코드입니다. import requests from bs4 import BeautifulSoup # beautiful soup 라이브러리 import base_url = "https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=" keyword = input("검색어를 입력하세요 : ") url = base_url + keyword print(url) headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36" } # dictionary req = requests.get(url, headers = headers) # GET 방식으로 naver에 요청 html = req.text # 요청을 하여 html을 받아옴 soup = BeautifulSoup(html, "html.parser") # html을 html.parser로 분석(클래스를 통한 객체 생성) items = soup.select(".total_wrap.api_ani_send") for area in items: # ad = area.select_one(".link_ad") # if ad: # print("광고입니다.") # continue title = area.select_one(".api_txt_lines.total_tit") name = area.select_one(".sub_txt.sub_name") print(title.text) print(name.text) # print(title["href"]) print() #print(len(items))
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=options) url = "https://naver.com" driver.get(url) 위 처럼 작성을 했는데 계속 꺼집니다. 현재 최신 버전이며, 구글링해서 찾아봐도 원인을 모르겠네요 ㅠ 짐작이 가는거는 버전이 달라서인데 현재 제 크롬은 최선 버전으로 115.0.5790.102 입니다. 그래서 https://googlechromelabs.github.io/chrome-for-testing/ 이 사이트에서 win64로 받았는데 시도했는데 현재 안되는 상태입니다
강의 : 네이버 쇼핑 크롤링 1 , 11:14 시점에서 막힙니다. from bs4 import BeautifulSoup import requests keyword = input("검색할 제품을 입력하세요 : ") url = "https://search.shopping.naver.com/search/all?query={keyword}" user_agent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Mobile Safari/537.36" headers = {'User-Agent': user_agent} req = requests.get(url, headers=headers) html = req.text # print(html[:1000]) 확인용 soup = BeautifulSoup(html, "html.parser") base_divs = soup.select("[class^=product_item]") # product_item 로 클래스 이름이 시작되는 클래스 # print(base_divs) print(len(base_divs)) for base_div in base_divs: title = base_div.select_one("[class^=product_link]") print(title.text) 우선 강의에서는 basicLis_item, basicList_link 로 했는데 현재 네이버 쇼핑몰에서는 product_item***, product_link*** 로 되어 있습니다. 아래 스샷처럼요. 그런데 코드를 치니까 이상한게 나와요 자꾸.. 이유가 뭘까요 ??
[현재 화면 크기 지정하는 옵션 추가, 유저 에이전트 사용법] 강의에서 <03:38> 지점에 대한 질문입니다. 제가 아래와 같은 코드를 실행 후 오류 메시지가 떴습니다. from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.0.0 Safari/537.36" options = Options() options.add_experimental_option("detach", True) options.add_argument(f"user-agent={user_agent}") # options.add_experimental_option("--start-maximized") # options.add_experimental_option("--start-fullscreen") options.add_argument("window-size=500, 500") service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome("../driver/chromedriver.exe", service = service, options=options) url = "https://naver.com" driver.get("url") time.sleep(2) AI 에게 질문을 해보니, 아래와 같은 해답을 내놓았는데, 어떻게 코드를 작성해야 할까요? 새로 업데이트 된 셀레니움에서도 service는 문제 없이 잘 돌아간다고 알고 있는데, 문제 발생 이유가 궁금합니다...
셀레니움 최신 버전에서 service를 쓸 수 없는데, 이제 다음과 같은 코드에서 option 기능은 어떻게 코드를 짜면 될까요? 아래 코드에서 service 부분을 빼야할까요? 셀레니움 버전 업그레이드와 함께 코드에서 수정할 부분이 있을까요? 위는 코드랑 출력 결과이고 아래는 코드만 따로 옮긴 것입니다. from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import time user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" options = Options() options.add_experimantal_option("detach", True) options.add_argument(f"user-agent={user_agent}") # options.add_argument("--start-maximized") # options.add_argument("--start-fullscreen") options.add_argument("window-size=500, 500") # driver = webdriver.Chrome("../driver/chromedriver.exe") service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options) url = "https://naver.com" driver.get(url)
src에서는 잘못된 썸네일 링크들이 간혹 있잖아요, 예를 들어 "// img1a.coupangcdn.com/image/coupang/search/blank1x1.gif " 이런 링크들이요 그런데 아래 이미지 처럼 왜 꼭 "페이지 소스 보기"에서 검색을 해야 링크가 어디 있는지 찾을 수 있고 왜 그냥 페이지에서 개발자 도구를 검색을 하면 이 잘못된 링크들은 검색이 되지를 않는거죠? 이렇게 여기서 검색을 하면 하나도 나오지 않습니다. 혹시 오류가 있는건지 원래 안뜨는건지.. 알 수 있을까요 ?(다른 올바른 썸네일 링크는 또 여기서 검색하면 뜨더라고요)
이렇게 코드 작성을 했는데, 강의와는 다르게 출력이 안되네요 현재 강의는 쿠팡 크롤링의 [상품 링크, 썸네일 url 가져오기] 이고, 시점은 04:14 입니다. 강의 영상 내 html하고 지금 쿠팡 html 하고 비교도 해봤는데 틀린 것이 없고 오타도 없는 것 같은데 문제가 뭘까요 ? import requests from bs4 import BeautifulSoup headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "accept-language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7" } cookie = {"a" : "b"} base_url = "https://www.coupang.com/np/search?component=&q=" keyword = input("검색어 입력하세요 : ") search_url = base_url + keyword req = requests.get(search_url, timeout=5, headers=headers, cookies=cookie) html = req.text soup = BeautifulSoup(html, "html.parser") items = soup.select("[class=search-product]") print(len(items)) rank = 1 for item in items: badge_rocket = item.select_one(".badge.rocket") if not badge_rocket: continue name = item.select_one(".name") price = item.select_one(".price-value") thumb = item.select_one("search-product-wrap-img") link = item.select_one("a")["href"] # or item.a["href"] print(f"{rank}위") print(name.text) print(f"{price.text} 원") # print(link) print(thumb["src"]) print() rank += 1 결과는 이렇게 뜨네요 쿠팡 html 입니다.
현재 네이버 view 탭 검색 결과 크롤링 3 , 10분 43초 지점입니다. 손흥민, 파이썬, 블랙핑크 검색해보고 개발자 탭에서 .api_ani_send 까지 각각 다 확인해서 강의 대로 타이핑 해서 쳤더니 전 0 이라고 나옵니다. 눈으로 직접 확인까지 하고 해보는데도 왜 에러가 나는 건가요 ? import requests from bs4 import BeautifulSoup keyword = input("검색어를 입력하세요. : ") base_url = "https://search.naver.com/search.naver?where=view&sm=tab_jum&query=" headers = {"User-Agent" : "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36"} url = base_url + keyword req = requests.get(url, headers=headers) html = req.text soup = BeautifulSoup(html, "html.parser") items = soup.select(".api_ani_send") for rank_num, area in enumerate(items, 1): print(f"<<<{rank_num}>>>") ad = area.select_one(".link_ad") if ad: print("광고입니다.") continue title = area.select_one(".api_txt_lines.total_tit") # 빈 칸을 . 으로 맞춰줘야한다. name = area.select_one(".sub_txt.sub_name") print(name.text) print(title.text) print(title['href']) print() print(len(items))
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/70.0.0.0 Safari/537.36" options = Options() options.add_experimental_option("detach", True) options.add_argument(f"user-agent={user_agent}") # options.add_argument("--start-maximized") # options.add_argument("--start-fullscreen") # options.add_argument("window-size=500,500") # options.add_argument("--headless") # options.add_argument("--disable-gpu") options.add_argument("--mute-audio") options.add_argument("incognito") service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options) url = "https://naver.com" driver.get(url) print(driver.page_source[:1000]) # driver.quit() 수업 진행을 그대로 따라 하였습니다. 다만 코드 실행은 잘 되지만 크롬창이 계속해서 종료가 되어 그것을 막는 코드를 입력해도 계속 자동 종료가 됩니다 저의 크롬 버전은 버전 114.0.5735.199(공식 빌드) (64비트) 이며 셀레니움 버전은 4.10.0 입니다! 진도를 따라 가고싶으나 계속해서 창이 꺼져 진행이 어렵습니다 ㅠㅠ 도움을 원합니다.
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("https://google.com") time.sleep(2) #2. 알아서 버전업을 해줌 별다른 반응이 없네요 ㅠ 맥북은
강의 내용 외 개인적인 실습 사이트의 질문은 답변이 제공되지 않습니다. 문제가 생긴 코드, 에러 메세지 등을 꼭 같이 올려주셔야 빠른 답변이 가능합니다. 답변은 바로 제공되지 않을 수 있습니다. 실력 향상을 위해서는 직접 고민하고 검색해가며 해결하는 게 가장 좋습니다. 셀레니움으로 알리익스프레스 로그인하려고 xpath 따서 해봐도 잘안되네요……
쓱닷컴 이벤트 주소는 아래와같습니다. https://shinsegaemall.ssg.com/event/eventMain.ssg?Sgnb=event 문제는 이벤트 페이지가 1, 2 이렇게 2개 존재합니다. 문제는 1 페이지를 클릭하던 2페이지를 클릭하던, 주소가 모두 같습니다. 1페이지 클릭시 -> https://shinsegaemall.ssg.com/event/eventMain.ssg?Sgnb=event 2페이지 클릭시-> https://shinsegaemall.ssg.com/event/eventMain.ssg?Sgnb=event 이럴때는 어떻게 해야하나요? 셀레니움이 답일까요?
"쿠팡 제품 검색 결과 크롤링" 강의를 응용해서 타오바오 사이트에서 해보려고 하는데, 자꾸 안돼서 아래와 같이 print(html) 했더니 뭔가 차단된거 같은 html 막 쭉 뜨네요 이럴때는 어떻게 해야하나요? req = requests.get(links, timeout=5, headers=headers, cookies=cookie) html = req.text soup = BeautifulSoup(html, "html.parser") print(html)
선생님! 쿠팡정보 크롤링해서 웹사이트 만들었습니다 이렇게 유익한 강의 처음입니다!! 너무너무 감사해요 다름이 아니라 혹시 괜찮으시면 선생님과 만든 웹사이트에 쿠팡 파트너스 API 연동시키는 부분 강의로 찍어주실수 있는지요 아님 유튜브 영상이라도 부탁드려요 ㅠㅠㅠ 혼자 하려니까 API 주소를 어따 붙여넣기 해야하는지 감이 안잡히네요
안녕하세요. 강의 잘 듣고 있습니다. 네이버가 새로운 형태로 바뀌었는데 아주 간단한 것이 해결이 안되네요? 이유가 뭘까요? 기본구조는 이렇게 생겼습니다. <li class="shortcut_item"> <a href="mail.naver.com" class="link_service"> <span class="service_icon type_mail"> ::before ::after </span> <span class="service_name">메일</span> </a> </li> <li class="shortcut_item"> </li> 아래처럼 너무 단순한거라 생각했던 것을 못 가져오네요? 확인 부탁드려요~ service_name = soup.find(class_="service_name", string="메일") print(service_name) # None 출력이 안되네 이유가 뭘까나? print()