[리뉴얼] 파이썬입문과 크롤링기초 부트캠프 [파이썬, 웹, 데이터 이해 기본까지] (업데이트)
위 페이지에서 기사 제목: 김혜수 "실패 없을 것 같은 내 이력..."<span class="text">를 출력하고자 합니다. select를 이용해서 출력하고자 하는데, 어떤 것이 잘못되었는지 모르겠습니다. items = soup.select ('ol#topViewArticlesContainer p.title span.text') ol id가 topViewArticlesContainer 밑에 p 태그의 class가 title인 것의 밑에 span 태그의 class가 text인 것을 뽑으려고 했는데,, 어떤게 잘못 된건지 알 수 있을까요?
아래와 같이 코드를 작성했습니다. Response를 안쓰고 진행했는데 뉴스기사는 출력이 되지만 연예기사가 출력이 안됩니다 ㅠㅠ from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup # 크롬 드라이버 자동 업데이트 from webdriver_manager.chrome import ChromeDriverManager import time import pyautogui import pyperclip import csv # 브라우저 꺼짐 방지 chrome_options = Options() chrome_options.add_experimental_option("detach", True) # 크롬창 안뜨게 함 chrome_options.add_argument('--headless') # headless 모드 활성화 chrome_options.add_argument('--disable-gpu') # GPU 가속 비활성화 # Mozilla 웹 브라우저에서 온 것처럼 인식 / 자동화된 요청을 감지하고 차단하는 것을 우회 chrome_options.add_argument("--user-agent=Mozilla/5.0") # 불필요 메세지 없애기 chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"]) # 드라이버 업데이트 service = Service(executable_path=ChromeDriverManager().install()) # 옵션 적용 browser = webdriver.Chrome(service=service, options=chrome_options) news = pyautogui.prompt('뉴스기사 입력 >>> ') print(f'{news} 검색') # 웹페이지 해당 주소 이동 path = f'https://search.naver.com/search.naver?where=news&sm=tab_jum&query={news}' # url 대화 browser.get(path) # 네이버에서 html 줌 html = browser.page_source soup = BeautifulSoup(html, 'html.parser') articles = soup.select("div.info_group") # 뉴스 기사 div 10개 추출 for article in articles: links = article.select("a.info") if len(links) >= 2: # 링크가 2개 이상이면 url = links[1].attrs['href'] # 두번째 링크의 href 추출 # 다시 한번 받아옴 browser.get(url) html = browser.page_source soup = BeautifulSoup(html, 'html.parser') # 연예뉴스라면 -> ? div 모양이 다름 if 'entertain' in url: title = soup.select_one(".end_tit") content = soup.select_one('#articeBody') else: title = soup.select_one("#title_area") content = soup.select_one('#dic_area') # 해당 링크 본문의 아이디값 가져옴 print("=============링크==========\n", url) print("=============제목==========\n", title.text.strip()) print("=============내용==========\n", content.text.strip()) time.sleep(0.7) print('\nDvlp.H.Y.C.Sol\n') 출력은 이렇게 나옵니다. =============링크========== https://n.news.naver.com/mnews/article/382/0001075938?sid=106 Traceback (most recent call last): File "c:\Users\cksth\OneDrive\바탕 화면\Career\크롤링\심화\02.연예뉴스.py", line 71, in <module> print("=============제목==========\n", title.text.strip()) AttributeError: 'NoneType' object has no attribute 'text
안녕하세요, 저번에 친절하게 답변해주셔서 감사합니다. 강의 수강 중에 크롤링 코드를 작성 후, 정상 작동을 확인한 다음에 다른 PC에서 파이썬/Visual Studio Code를 설치하여 파일을 실행했는데, 정상적으로 크롤링이 작동하지 않는 오류가 발생했습니다 ㅜㅜ 처음에는 라이브러리 설치를 전부 진행했었는데, 아래와 같은 오류가 발생했었습니다 [현재는 해결된 현상] import 모듈(?) 오류 import requests 를 작성하면 requests 부분이 초록색이 되어야 하는데, 흰 글씨가 되는 현상 pip install --upgrade 오류 해당 명령어를 사용하면 upgrade가 진행되지 않고, ERROR : You must give at least one requirement to install (see "pip help install") 이라는 문구만 출력됩니다. (혹시 몰라서 원래 잘 되던 기존 PC에 입력해보니까 다른 명령어로 쓰라면서 notice가 출력됐었습니다. 기존 PC에서는 아무런 설명도 없이 오류만 떠요ㅜㅜ) 일단 기본적으로 코드를 실행하면 크롤링 후에 엑셀 파일이 생성되어야 하는데 결과적으로는 안 됩니다..혹시 도움을 받을 수 있을까요? 현재까지 시도해 본 것들 1) Python , Visual Studio Code 삭제 및 재설치 , 윈도우 버전 확인 등 2) Python 환경 변수 설정 (기존 PC에는 따로 환경 변수 설정을 하지 않아도 잘 작동하는 점 확인) 3) Visual Studio Code 재실행, 컴퓨터 재부팅 4) cmd 에서 Python 정상 설치 확인 5) pip 삭제 후 재설치 진행 (upgrade는 못한 상태 6) 기존 PC와 현 PC의 코드 크로스 체크 (특이사항 없음 확인)
네이버 쇼핑 최저가 검색 코드를 ChatGpt에게 문의하는 부분에서 강사님과 다른 코드를 작성해 답변해 줍니다. import requests from bs4 import BeautifulSoup # Naver 쇼핑에서 특정 제품의 최저 가격 정보를 검색하려면 Python을 사용할 수 있습니다. # 아래는 시작하기 위한 Python 코드 예제입니다. # 특정 제품에 대한 Naver 쇼핑 검색 결과 페이지의 URL을 지정합니다. product_url = ' https://search.shopping.naver.com/search/all?query=여기에_제품_이름_입력 ' # URL로 GET 요청을 보냅니다. response = requests.get(product_url) # 요청이 성공했는지 확인합니다 (상태 코드 200). if response.status_code == 200: # 페이지의 HTML 내용을 파싱합니다. soup = BeautifulSoup(response.text, 'html.parser') # 제품 이름 및 가격과 같은 제품 정보를 포함하는 요소를 찾습니다. product_elements = soup.find_all('div', class_='basicList_info_area__17Xyo') if product_elements: # 최저 가격과 제품 이름을 추적하는 변수를 초기화합니다. lowest_price = None product_name = None for product in product_elements: # 제품 이름과 가격을 추출합니다. name = product.find('a', class_='basicList_link__1MaTN').text.strip() price = product.find('span', class_='price_num__2WUXn').text.strip() # 가격을 정수로 변환합니다 (화폐 기호, 쉼표 등을 제거합니다). price = int(price.replace('원', '').replace(',', '')) # 최저 가격을 찾았거나 또는 최저 가격이 아직 없는 경우 업데이트합니다. if lowest_price is None or price < lowest_price: lowest_price = price product_name = name if lowest_price is not None and product_name is not None: # 최저 가격과 제품 이름을 출력합니다. print(f"'{product_name}' 제품의 최저 가격은 {lowest_price} 원입니다.") else: print("제품 정보를 찾을 수 없습니다.") else: print("페이지에서 제품 정보를 찾을 수 없습니다.") else: print("웹페이지 검색에 실패했습니다. URL 또는 네트워크 연결을 확인하세요.") 이런 코드를 gpt가 제공하는데 어떻게 해야 강사님과 같은 코드가 출력 될까요?
# 랜덤 패턴 가지고오기 def get_random_pattern(isMobile=True): ret_pattern = [] if isMobile: with open("./mobile_scroll.txt","r") as f : while True: line = f.readline() if not line: break ret_pattern.append(line.rstrip()) selected_pattern = random.choice(ret_pattern) _,sx,sy,delay = selected_pattern.split("#") if abs(int(sy)) < 15 or float(delay) < 0.25: #너무 적은 값 return get_random_pattern(isMobile) return int(sx), int(sy), float(delay) else: # PC 패턴 with open("./pc_scroll.txt", "r") as f: while True: line = f.readline() if not line: break ret_pattern.append(line.rstrip()) pc_scroll_px = 114 # 100, 114 selected_pattern = random.choice(ret_pattern) _,dx,dy,delay = selected_pattern.split("#") if float(delay) < 0.25: return get_random_pattern(isMobile) return int(dx),int(pc_scroll_px), float(delay) 질문1. 위 패턴에서 pc_scroll_px 를 114로 하는 이유를 잘 모르겠습니다. 저는 모바일 말고 pc로 작업을 해보려고하는데 114씩만 올라갔다 내려갔다 스크롤되는데 전혀 사람처럼 보이지 않고 부자연스러워 보입니다. ㅜ def random_move(driver,direction="down",count=1,isMobile=True): for _ in range(count): # [O] 사람패턴 ~ 사람이 얼마나 스크롤을 움직였는지 # randY = random.randrange(200,300) randX,randY,_delay = get_random_pattern(isMobile) sx = random.randrange(100,270) sy = random.randrange(250,500) if direction == "up": randY = -randY if random.random() > 0.9 : #10%의 확률로 randY = -randY print(f"Scroll 한다 {randY}") ActionChains(driver).scroll_by_amount(0, randY).perform() # [O] 사람패턴 ~ 스크롤 하는 텀 prob = random.random() if prob < 0.5: dt = random.uniform(_delay*0.1, _delay*0.3) elif prob < 0.8: dt = random.uniform(_delay*0.2, _delay*0.6) else: dt = random.uniform(_delay*0.5, _delay*1.2) time.sleep(dt) time.sleep( 0.5) 질문2. 매개변수로 count를 받고있는데 이 부분을 넣은 이유를 정확하게 모르겠네요. ㅜ 그리고 sx = random.randrange(100,270) sy = random.randrange(250,500) 이렇게 받아둔 변수를 어떻게 활용하는지 강사님께서는 어떻게 사용하는지 궁금합니다.
''' 네이버지도에 표시되는 순서대로 순위, 가게명, 별점, 방문자리뷰수, 블로그리뷰수를 엑셀에 저장(1페이지만) 주의사항 광고는 제외, 별점이 있는 가게만 크롤링한다. 방문자 리뷰가 없다면 0으로 수집, 블로그 리뷰가 없다면 0으로 수집한다. iframe을 만났을때 대처방법. 무한 스크롤 처리 방법 고민. ''' from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import pyautogui import time from bs4 import BeautifulSoup import openpyxl #크롬 드라이버 자동 업데이트 from webdriver_manager.chrome import ChromeDriverManager header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36', } keyword = pyautogui.prompt("검색어를 입력하세요>>>") wb = openpyxl.Workbook() ws = wb.create_sheet(keyword) ws.append(["순위","가게명","별점","방문자 리뷰수","블로그 리뷰수"]) chrome_options = Options() #브라우저 꺼짐 방지 chrome_options.add_experimental_option("detach", True) #불필요한 에러 메시지 없애기 chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"]) # 셀레니움 로그 무시 serivce = Service(executable_path=ChromeDriverManager().install()) browser = webdriver.Chrome(service=serivce, options=chrome_options) #웹페이지 해당 주소 이동 browser.implicitly_wait(5) browser.maximize_window() browser.get("https://map.naver.com/p?c=15.00,0,0,0,dh") search = browser.find_element(By.CSS_SELECTOR,".input_search") search.click() time.sleep(1) search.send_keys(f"{keyword}") time.sleep(1) search.send_keys(Keys.ENTER) time.sleep(1) #iframe 안으로 들어가기 browser.switch_to.frame("searchIframe") #iframe 밖으로 나오기 #browser.switch_to.default_content() browser.find_element(By.CSS_SELECTOR,"#_pcmap_list_scroll_container").click() lists = browser.find_elements(By.CSS_SELECTOR,"li.UEzoS") before_scroll = len(lists) while True : before_scroll = len(lists) for i in range(0,10) : browser.find_element(By.CSS_SELECTOR,"body").send_keys(Keys.PAGE_DOWN) time.sleep(0.5) lists = browser.find_elements(By.CSS_SELECTOR,"li.UEzoS") after_scroll = len(lists) if before_scroll == after_scroll : break # lists = browser.find_elements(By.CSS_SELECTOR,"li.UEzoS.rTjJo") print(f"총 {after_scroll}개의 가게가 있습니다.") num = 0 for list in lists : if len(list.find_elements(By.CSS_SELECTOR,"li>a.gU6bV")) == 0 : store = list.find_element(By.CSS_SELECTOR,"span.TYaxT") browser.execute_script("arguments[0].click();", store) time.sleep(1) browser.switch_to.default_content() browser.switch_to.frame("entryIframe") # html_entry = browser.page_source # soup_entry = BeautifulSoup(html_entry, 'html.parser') if len(browser.find_elements(By.CSS_SELECTOR,"#app-root > div > div > div > div.place_section.OP4V8 > div.zD5Nm.f7aZ0 > div.dAsGb > span.PXMot.LXIwF")) > 0 : num += 1 title = browser.find_element(By.CSS_SELECTOR,".Fc1rA").text stars = float(browser.find_element(By.CSS_SELECTOR,".LXIwF > em").text) visitor_review = browser.find_element(By.CSS_SELECTOR,"div.dAsGb > span:nth-child(2)").text blog_review = browser.find_element(By.CSS_SELECTOR,"div.dAsGb > span:nth-child(3)").text visitor_review = int(visitor_review.replace("방문자리뷰 ","").replace(",","")) blog_review = int(blog_review.replace("블로그리뷰 ","").replace(",","")) print(num,title,stars,visitor_review,blog_review) ws.append([num,title,stars,visitor_review,blog_review]) browser.switch_to.default_content() browser.switch_to.frame("searchIframe") wb.save(f"/Chapter05/{keyword}.xlsx") 안녕하세요 강사님. 현재 네이버 지도에서 강남역 맛집을 검색하면 강의 노트와 같이 방문자 리뷰, 블로그 리뷰를 크롤링하기 위해서는 해당 가게를 클릭하고 그 iframe으로 들어가서 데이터를 받아와야합니다. 그래서 위와 같이 코드를 작성하였는데요. 문제는 가게이름 클릭 후 페이지 로딩을 고려한 지연시간을 1초 밖에 안줬는데. 가게이름, 별점, 리뷰수를 읽어오는데 굉장히 오래걸립니다.(5~6초 이상 소요). 이 때문에 전체 리스트에 대한 정보를 받아오는 시간이 너무 많이 소요되는데요. 혹시 이를 개선할수있는 방안이 있을까요?
user-agent를 변경하고 실행해도 pc에서 접속한 것처럼 보입니다. 제 코드는 아래와 같으며 파이참에서 작성했습니다. from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time # 모바일에서 접속한 것처럼 보이게 하기 user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" options = Options() options.add_experimental_option("detach",True) # 화면이 안꺼지는 옵션 options.add_argument("--start-maximized") options.add_argument(f"user_agent={user_agent}") service = Service(ChromeDriverManager().install()) #크롬 드라이버를 자동설치하는 서비스를 만듬 driver = webdriver.Chrome(service=service,options=options) url = "https://m2.melon.com/index.htm" driver.get(url) if driver.current_url != url: driver.get(url) time.sleep(2)
''' 아래 키워드별로 순위, 브랜드명, 제품명, 가격, 상세페이지링크를 엑셀에 저장하기(1~100위 까지) [게이밍마우스, 기계식 키보드, 27인치 모니터] ※ 주의사항 - 광고 상품은 제외한다 (AD라고 표기됨) - 브랜드명이 없거나 이상하면 빈칸 ''' import requests from bs4 import BeautifulSoup import time import pyautogui # 헤더에 User-Agent, Accept-Language 를 추가하지 않으면 멈춥니다 header = { 'Host': 'www.coupang.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3', } url = f'https://www.coupang.com/np/search?component=&q=%EA%B2%8C%EC%9D%B4%EB%B0%8D+%EB%A7%88%EC%9A%B0%EC%8A%A4&channel=user' response = requests.get(url, headers=header) html = response.text soup = BeautifulSoup(html, 'html.parser') items = soup.select("div.descriptions-inner") for item in items : name = soup.select_one("div.name").text print(name) 쿠팡 첫페이지에서 '게이밍 마우스' 검색하여 각 상품별 이름을 가져오는 코드를 작성했는데요. (강의에서처럼 상품별 url에 들어가서 가져오는 것이 아닌, 검색 완료 페이지에서 바로 가져오기) 각 상품별로 div의 descriptions-inner tag를 가지고있고 div의 name tag를 가지고있어 해당 방법으로 가져오기를 해봤습니다. 위와 같이 실행을 하면 상품별 이름을 가져오기는 하는데 해당 페이지내 랜덤한 상품명이 하나로 쭉 나오는데... 어디서 잘못된걸까요? (결과는 아래 처럼 페이지중 하나의 상품명이 쭉나옵니다.) 로지텍코리아 (정품) 로지텍 G502 X PLUS 무선 게이밍 마우스, 블랙 로지텍코리아 (정품) 로지텍 G502 X PLUS 무선 게이밍 마우스, 블랙 로지텍코리아 (정품) 로지텍 G502 X PLUS 무선 게이밍 마우스, 블랙 로지텍코리아 (정품) 로지텍 G502 X PLUS 무선 게이밍 마우스, 블랙 로지텍코리아 (정품) 로지텍 G502 X PLUS 무선 게이밍 마우스, 블랙 로지텍코리아 (정품) 로지텍 G502 X PLUS 무선 게이밍 마우스, 블랙