묻고 답해요
130만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[2024 개정판] 이것이 진짜 크롤링이다 - 기본편
Chapter03에서 Beautifulsoup에서 원하는 결과가 안나오네요
Chapter03에서 Beautifulsoup라이브러리를 실습을 해보는데 결과가 <div class="talk_area" id="topTalkArea"></div>이렇게 div 밖에 안나오는데 뭔가 잘 못된건가요? 물론 id를 사지고 해봤네요..word = soup.select_one('#topTalkArea') 라고 했는데 <div class="talk_area" id="topTalkArea"></div> 이렇게밖에 안나왔네요...
-
미해결[2024 개정판] 이것이 진짜 크롤링이다 - 기본편
1페이지만 가져와집니다
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 두 코드 모두 1페이지만 불러와집니다ㅠㅠ어디가 잘못된걸까요 1페이지입니다.================== "암 걸리면 서울로"…5년간 100만명 방문 http://www.wowtv.co.kr/NewsCenter/News/Read?articleId=A202310050023&t=NN 두경부암 환자 괴롭히는 ‘구강점막염’ 새 치료법은 http://www.fnnews.com/news/202310040921133037 조기 유방암 환자, 유전자 재발 예측 점수 낮더라도 방심은 금물 http://www.edaily.co.kr/news/newspath.asp?newsid=01715446635770296 ‘이곳’ 사는 여성, 비만 관련 암 위험 낮아 https://health.chosun.com/site/data/html_dir/2023/10/05/2023100502500.html GC셀, 고형암 표적 CAR-NK세포치료제 다국가 1상 진행 http://www.medisobizanews.com/news/articleView.html?idxno=110729 인천 학교 급식실 노동자 폐암 발병 지속…"지원책은 미비" https://www.yna.co.kr/view/AKR20231005074500065?input=1195m 제주 암 환자 3만여 명, 5년간 '서울 원정 치료' http://www.jibs.co.kr/news/articles/articlesDetail/34499?feed=na 암 백신 청신호까지 켰다… 커리코 ‘30년 집념’ https://www.seoul.co.kr/news/newsView.php?id=20231004006003&wlog_tag3=naver 젠큐릭스, 갑상선암 동반진단 UAE 승인 …폐암 이어 두 번째 https://www.hankyung.com/article/202310057966i [약손+] 폐암의 진단과 치료 ⑩폐암의 유전과 가족력 https://dgmbc.com/article/fwzGgK5QFfpv 2페이지입니다.================== "암 걸리면 서울로"…5년간 100만명 방문 http://www.wowtv.co.kr/NewsCenter/News/Read?articleId=A202310050023&t=NN 두경부암 환자 괴롭히는 ‘구강점막염’ 새 치료법은 http://www.fnnews.com/news/202310040921133037 조기 유방암 환자, 유전자 재발 예측 점수 낮더라도 방심은 금물 http://www.edaily.co.kr/news/newspath.asp?newsid=01715446635770296 ‘이곳’ 사는 여성, 비만 관련 암 위험 낮아 https://health.chosun.com/site/data/html_dir/2023/10/05/2023100502500.html GC셀, 고형암 표적 CAR-NK세포치료제 다국가 1상 진행 http://www.medisobizanews.com/news/articleView.html?idxno=110729 인천 학교 급식실 노동자 폐암 발병 지속…"지원책은 미비" https://www.yna.co.kr/view/AKR20231005074500065?input=1195m 제주 암 환자 3만여 명, 5년간 '서울 원정 치료' http://www.jibs.co.kr/news/articles/articlesDetail/34499?feed=na 암 백신 청신호까지 켰다… 커리코 ‘30년 집념’ https://www.seoul.co.kr/news/newsView.php?id=20231004006003&wlog_tag3=naver 젠큐릭스, 갑상선암 동반진단 UAE 승인 …폐암 이어 두 번째 https://www.hankyung.com/article/202310057966i [약손+] 폐암의 진단과 치료 ⑩폐암의 유전과 가족력 https://dgmbc.com/article/fwzGgK5QFfpv 3페이지입니다.================== "암 걸리면 서울로"…5년간 100만명 방문 http://www.wowtv.co.kr/NewsCenter/News/Read?articleId=A202310050023&t=NN 두경부암 환자 괴롭히는 ‘구강점막염’ 새 치료법은 http://www.fnnews.com/news/202310040921133037 조기 유방암 환자, 유전자 재발 예측 점수 낮더라도 방심은 금물 http://www.edaily.co.kr/news/newspath.asp?newsid=01715446635770296 ‘이곳’ 사는 여성, 비만 관련 암 위험 낮아 https://health.chosun.com/site/data/html_dir/2023/10/05/2023100502500.html GC셀, 고형암 표적 CAR-NK세포치료제 다국가 1상 진행 http://www.medisobizanews.com/news/articleView.html?idxno=110729 인천 학교 급식실 노동자 폐암 발병 지속…"지원책은 미비" https://www.yna.co.kr/view/AKR20231005074500065?input=1195m 제주 암 환자 3만여 명, 5년간 '서울 원정 치료' http://www.jibs.co.kr/news/articles/articlesDetail/34499?feed=na 암 백신 청신호까지 켰다… 커리코 ‘30년 집념’ https://www.seoul.co.kr/news/newsView.php?id=20231004006003&wlog_tag3=naver 젠큐릭스, 갑상선암 동반진단 UAE 승인 …폐암 이어 두 번째 https://www.hankyung.com/article/202310057966i [약손+] 폐암의 진단과 치료 ⑩폐암의 유전과 가족력 https://dgmbc.com/article/fwzGgK5QFfpv import requests from bs4 import BeautifulSoup import pyautogui keyword = pyautogui.prompt("검색어를 입력하세요>>>") pageNum = 1 for i in range(1,30,10):#페이지넘기기 print(f"{pageNum}페이지입니다.==================")#페이지안내 response = requests.get(f"https://search.naver.com/search.naver?where=news&sm=tab_jum&query={keyword}&start{i}") #start숫자가페이지 html = response.text soup = BeautifulSoup(html, 'html.parser') links = soup.select(".news_tit") #결과는 리스트로 for link in links: title = link.text #태그 안에 텍스트요소를 가져온다 url = link.attrs['href'] #href의 속성값을 가져온다 print(title, url) pageNum = pageNum+1import requests from bs4 import BeautifulSoup import pyautogui keyword = pyautogui.prompt("검색어를 입력하세요>>>") lastpage = pyautogui.prompt("마지막 페이지번호를 입력해 주세요") pageNum = 1 for i in range(1,int(lastpage)*10,10): print(f"{pageNum}페이지입니다.==================") response = requests.get(f"https://search.naver.com/search.naver?where=news&sm=tab_jum&query={keyword}&start{i}") html = response.text soup = BeautifulSoup(html, 'html.parser') links = soup.select(".news_tit") #결과는 리스트로 for link in links: title = link.text #태그 안에 텍스트요소를 가져온다 url = link.attrs['href'] #href의 속성값을 가져온다 print(title, url) pageNum = pageNum + 1
-
미해결파이썬 셀레니움 고급편 (python selenium - 크롤링, 크롤러)
5.Bot Detection 피하기(고급편) 질문입니다.
options = uc.ChromeOptions()가져와서 아래쪽에 uc.Chrome() 실행할때 options가 안넣어져 있는데 안넣고 실행하는건가요???깃허브에 설명에는driver = uc.Chrome(options=options) 이렇게 되어 있어 보이는데요?
-
해결됨실습으로 끝장내는 웹 크롤링과 웹 페이지 자동화 & 실전 활용
selenium으로 연 크롬창 안꺼짐
셀레니움 버전도 3.14?였나 최신걸로 업데이트 하고 써서웹드라이버 설치하는 것도 안해도 되는 상태인데요.강의에서는 driver.get(url) 하면 창이 켜졌다 자동으로 꺼지던데제꺼는 창이 자동으로 안꺼집니다... 뭔가 업데이트로 변경된 부분인가요? 창 안꺼지도록 하는 방법 강의 들으려는데제꺼는 원래 안꺼져서 당황스럽네요
-
미해결초간단 초스피드 데이터 수집 (파이썬 크롤링)
안녕하세요 파이썬 관련 문의드립니다
안녕하세요 파이썬 공부하다가 도저히 모르겠어서 문의 드립니다.다름이 아니라 api 쪽은 공부해본적이 없어서 기본적인 걸 모르는것같은데http://ipss1.interpark.com/openapi/product/ProductAPIService.do?_method=UpdateProductAPIStatTpQty&citeKey={citeKey}&secretKey={secretKey}&dataUrl=https://shop.interpark.com/api/new.ver2/sample/sample9.xml사이트에서는 이방식으로 api 요청하라고 하는데코드는 챗gpt랑 하면서 짜봤는데import requests# API 엔드포인트 및 인증 정보 설정citeKey = "citeKey"secretKey = "secretKey"url = f"http://ipss1.interpark.com/openapi/product/ProductAPIService.do?_method=UpdateProductAPIStatTpQty&citeKey={citeKey}&secretKey={secretKey}"# 요청 데이터 설정 (상품 정보 업데이트)payload = { "prdNo": "12344452", # 인터파크 상품번호 (as a string) "saleStatTp": "03", # 판매중:01, 품절:02, 판매중지:03, 일시품절:05, 상품삭제:98}# API 요청 보내기response = requests.post(url, data=payload)# 응답 확인if response.status_code == 200: print(response.text)else: print("상품 정보 업데이트에 실패했습니다.") print("응답 코드:", response.status_code) print("응답 내용:", response.text)제가 짠 코드에선 url 맨뒤에 예시처럼&dataUrl=https://shop.interpark.com/api/new.ver2/sample/sample9.xml이부분이 빠진것같은데patload 부분을 예시처럼 url을 만들어서 저렇게 하는방식이 가능한가요?
-
해결됨실습으로 끝장내는 웹 크롤링과 웹 페이지 자동화 & 실전 활용
string vs text
text가 하위 태그에 있는 문자열까지 가져온다는 것은 알겠습니다. 근데 string도 명확한 설명 부탁드립니다..강의에서 <a class="logo_naver"> <span class="blind">네 이버</span></a>이걸로 예를 들었는데.. 공백도 문자열이잖아요. 강의에서도 그렇게 말씀하셨고.그러면 위 html코드에 string을 불러오면 a태그 뒤의 공백 한칸을 가져와서 " " 이런 공백 한칸으로 이루어진 문자열이 나와야 할 것 같은데 None으로 나오죠..문자열인데 왜 None으로 나오는지 잘 모르겠습니다.엔터가 들어가도 None으로 나오는 것 같은데... text는 알겠는데 string은 설명이 좀 부족한것 같아서 보충 설명 부탁드립니다.
-
미해결이것이 진짜 크롤링이다 - 실전편
불필요한 div, p 코드 삽입 후 에러
안녕하세요. 샘불필요한 div, p 코드 사입 후 에러 발생 건 입니다. import requests from bs4 import BeautifulSoup import time req_header_dict = { # 요청헤더 : 브라우저 정보 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36' } response = requests.get("https://search.naver.com/search.naver?where=news&sm=tab_jum&query=%EC%86%90%ED%9D%A5%EB%AF%BC", headers= req_header_dict) 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") # 결과는 리스트 if len(links) >= 2: url = links[1].attrs["href"] response = requests.get(url, headers= req_header_dict) html = response.text soup = BeautifulSoup(html, "html.parser") # 만약 뉴스라면 if "entertain" in response.url: title = soup.select_one(".end_tit") content = soup.select_one("#articeBody") # 스포츠 뉴스라면 elif "sports" in response.url: title = soup.select_one("h4.title") content =soup.select_one("#newsEndContents") # 본문 내용안에 불필요한 dvi 삭제 divs = content.select("div") for div in divs: div.decompose() paragraphs = content.select("p") for p in paragraphs: p.decompose() else: title = soup.select_one(".tit.title_area") content = soup.select_one("#newsct_article") print("##########링크##########",url) print("##########제목##########",title.text.strip()) print("##########본문##########",content.text.strip()) time.sleep(0.3)
-
미해결실습으로 끝장내는 웹 크롤링과 웹 페이지 자동화 & 실전 활용
html 출력문제
강의 내용 외 개인적인 실습 사이트의 질문은 답변이 제공되지 않습니다.문제가 생긴 코드, 에러 메세지 등을 꼭 같이 올려주셔야 빠른 답변이 가능합니다.코드를 이미지로 올려주시면 실행이 불가능하기 때문에 답변이 어렵습니다.답변은 바로 제공되지 않을 수 있습니다.실력 향상을 위해서는 직접 고민하고 검색해가며 해결하는 게 가장 좋습니다. import requestsfrom bs4 import BeautifulSoup url = "https://naver.com" req = requests.get(url) html = req.text print(html)주피터 노트에서는 실행이 되는데 비쥬얼스튜디오에서는 결과가 이렇게 나왔습니다. PS C:\Users\pw720> & C:/Users/pw720/AppData/Local/Programs/Python/Python311/python.exeon.exe AMD64)] on win32Python 3.11.5 (tags/v3.11.5:cce6ba9, Aug 24 2023, 14:38:34) [MSC v.1936 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> print(html)Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'html' is not defined>>> print(html)Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'html' is not defined>>> beautifulsoup4설치가 안되는것같아 cmd에서 설치했는데 제대로 안깔려서 안되는건가요?
-
미해결[2024 개정판] 이것이 진짜 크롤링이다 - 기본편
네이버 자동로그인
안녕하세요 네이버 자동로그인을 실행하면로그인 창이 떠요.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 webdriver_manager.chrome import ChromeDriverManager # 브라우저 꺼짐 방지 chrome_options = Options() chrome_options.add_experimental_option('detach',True) # 불필요한 에러 메시지 없애기 chrome_options.add_experimental_option('excludeSwitches',['enable-logging']) service = Service(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service,options=chrome_options) # 웹페이지 해당 주소 이동 driver.implicitly_wait(5) driver.maximize_window() driver.get('https://nid.naver.com/nidlogin.login?mode=form&url=https://www.naver.com/') # 아이디 입력 창 driver.find_element(By.CSS_SELECTOR,'#id') id.click() id.send_keys('sand12') # 비밃번호 입력 창 pw = driver.find_element(By.CSS_SELECTOR,'#pw') pw.click() pw.send_keys('yiiit!@') # 로그인 버튼 login_btn = driver.find_element(By.CSS_SELECTOR,'#log\.login') login_btn.click()
-
미해결[2024 개정판] 이것이 진짜 크롤링이다 - 기본편
네이버 자동 로그인
안녕하세요 네이버 자동로그인 실행하면 네이버 로그인창이 떠요
-
미해결[2024 개정판] 이것이 진짜 크롤링이다 - 기본편
vscode terminal 설정
안녕하세요 vscode terminal에서 cmd로 설정하면 한 번은cmd로 실행되고 두번 째 는 cmd 아래 python으로 실행됩니다여러가지로 cmd를 설정해도 마찬가지입니다답변 부탁드리면서 안녕히 계세요
-
미해결이것이 진짜 크롤링이다 - 실전편
구글 이미지 주소 추출 - 오류(고양이)
*. 질문 : 큰 이미지 주소추출에서 문제가 발생하는 듯 합니다. 해결점을 못 찾겠습니다. "고양이" 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 os import urllib.request import pyautogui # keyword = pyautogui.prompt("검색어를 입력하세요") if not os.path.exists("고양이"): os.mkdir("고양이") # 크롬 드라이버 자동 업데이트 from webdriver_manager.chrome import ChromeDriverManager import time import pyautogui import pyperclip # 브라우저 꺼짐 방지 chrome_options = Options() chrome_options.add_experimental_option("detach", True) # 불필요한 에러 메시지 없애기 chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"]) service = Service(executable_path=ChromeDriverManager().install()) browser = webdriver.Chrome(service=service, options=chrome_options) # 웹페이지 해당 주소 이동 browser.implicitly_wait(10) # 웹페이지 로딩 될때가지 5초는 기다림 browser.maximize_window() #browser = webdriver.Chrome() browser.get("https://www.google.co.kr/search?q=%EA%B3%A0%EC%96%91%EC%9D%B4&tbm=isch&ved=2ahUKEwioo8HqscOBAxUM_WEKHdO9CDwQ2-cCegQIABAA&oq=%EA%B3%A0%EC%96%91%EC%9D%B4&gs_lcp=CgNpbWcQAzIECCMQJzIICAAQgAQQsQMyCAgAEIAEELEDMggIABCABBCxAzIICAAQgAQQsQMyCAgAEIAEELEDMggIABCABBCxAzIFCAAQgAQyCAgAEIAEELEDMgUIABCABDoLCAAQgAQQsQMQgwFQ9hJYiRlg7hpoAXAAeACAAY8BiAGMB5IBAzEuN5gBAKABAaoBC2d3cy13aXotaW1nwAEB&sclient=img&ei=eT4QZeiCOoz6hwPT-6LgAw&bih=933&biw=1680") before_h = browser.execute_script("return window.scrollY") # 무한 스크롤 while True: browser.find_element(By.CSS_SELECTOR, "body").send_keys(Keys.END) time.sleep(1) after_h = browser.execute_script("return window.scrollY") if after_h == before_h: break before_h = after_h # 썸네일 이미지 태크 추출 imgs = browser.find_elements(By.CSS_SELECTOR,".rg_i.Q4LuWd") for i, img in enumerate(imgs,1): # 각 이미지를 클릭해서 큰 사이즈를 찾음 img.click() time.sleep(2) # 큰 이미지 추출 target = browser.find_element("img.r48jcc.pT0Scc.iPVvYb") img_src = target.get_attribute("src") # 이미지 다운로드 # 크롤링 하다보면 http error 403: forbidden 에러가 납니다. opener = urllib.request.build_opener() opener.addheaders = [("User-Agent","Mozila/5.0")] urllib.request.install_opener(opener) urllib.request.urlretrieve(img_src,f"고양이{i}.jpg") # 이미지 저장
-
미해결파이썬입문과 크롤링기초 부트캠프 [파이썬, 웹, 데이터 이해 기본까지] (업데이트)
굳굳
좋아요! 완전 초보들은 다운로드 받을 수 도 없어요.. 첫 시작에 도움이 많이 됩니다. 이렇게 다운로드 하나하나 전부 설명해주는거 너무 좋아요. 그래서 결제했어요. 공부 다했는데 처음부터 까먹어서 ㅠㅠ 다시 봣네요 감사합니다
-
미해결이것이 진짜 크롤링이다 - 실전편
selenium 에서 웹드라이버를 불러오지 못하는 오류납니다~
Microsoft Windows [Version 10.0.19045.3448](c) Microsoft Corporation. All rights reserved.C:\Users\user\data>C:/Users/user/AppData/Local/Programs/Python/Python311/python.exe c:/Users/user/data/sel.pyTraceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 38, in get_path path = SeleniumManager().driver_location(options) if path is None else path ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\common\selenium_manager.py", line 76, in driver_location browser = options.capabilities["browserName"] ^^^^^^^^^^^^^^^^^^^^AttributeError: 'str' object has no attribute 'capabilities'During handling of the above exception, another exception occurred:Traceback (most recent call last): File "c:\Users\user\data\sel.py", line 33, in <module> File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in init super().__init__( File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 51, in init self.service.path = DriverFinder.get_path(self.service, options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 40, in get_path msg = f"Unable to obtain driver for {options.capabilities['browserName']} using Selenium Manager." ^^^^^^^^^^^^^^^^^^^^
-
미해결R로 하는 웹 크롤링 - 입문편
htmltab 패키지에서 url을 불러올 수 없습니다.
주식데이터 크롤링을 수강하고 있습니다. htmltab 패키지 설치 후 url를 정상적으로 입력을 했는데도 Error: Couldn't find a table. 이라는 메세지가 나옵니다. 무엇이 잘못되었을까요...
-
미해결이것이 진짜 크롤링이다 - 실전편
크롤링 에러 관련 문의
안녕하세요.아래 코드를 사용해서 '식품 로봇'이라는 검색어로 크롤링을 시도했는데요. URL에 지정한 기간에 존재하는 모든 기사를 수집하고자 하는데, 총 몇 페이지나 있는지 알 수가 없어서.. 페이지수를 2,000으로 넣어서 실행 해보았습니다.그런데, 크롤링이 잘 진행되다가 에러가 발생해서요. 혹시 이건 어떻게 수정할 수 있을지요?에러 문구:=======링크======= https://n.news.naver.com/mnews/article/025/0003239249?sid=101 Traceback (most recent call last): File "/Users/유저이름/startcoding/Chapter04/11.마지막페이지확인하기.py", line 64, in <module> print("=======제목======= \n", title.text.strip()) ^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'text'실행 코드:import requests from bs4 import BeautifulSoup import time import pyautogui from openpyxl import Workbook from openpyxl.styles import Alignment # 사용자입력 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 = 60 ws.column_dimensions['C'].width = 120 # 행 번호 row = 1 # 페이지 번호 page_num = 1 for i in range(1, lastpage * 10, 10): print(f"{page_num}페이지 크롤링 중 입니다.==========================") response = requests.get(f"https://search.naver.com/search.naver?sm=tab_hty.top&where=news&query={keyword}&start={i}") html = response.text # html은 response의 text 안에 위치함 soup = BeautifulSoup(html, 'html.parser') articles = soup.select("div.info_group") #뉴스 기사 div 10개 추출 # 기사가 10개니까 for문을 써서 하나하나 추출 필요 for article in articles: links = article.select("a.info") # a 태그, info class인 아이들을 가져옴. = 리스트 if len(links) >= 2: # 링크가 2개 이상이면 url = links[1].attrs['href'] # 두번째 링크의 href를 추출 # 다시 request 날려주기 response = requests.get(url, headers={'User-agent': 'Mozila/5.0'}) html = response.text soup_sub = BeautifulSoup(html, 'html.parser') print(url) # 연예 뉴스 체크 if "entertain" in response.url: title = soup_sub.select_one(".end_tit") content = soup_sub.select_one("#articeBody") elif "sports" in response.url: title = soup_sub.select_one("h4.title") content = soup_sub.select_one("#newsEndContents") # 본문 내용 안에 불필요한 div, p 삭제 divs = content.select("div") for div in divs: div.decompose() paragraphs = content.select("p") for p in paragraphs: p.decompose() else: title = soup_sub.select_one(".media_end_head_headline") content = soup_sub.select_one("#newsct_article") print("=======링크======= \n", url) print("=======제목======= \n", title.text.strip()) print("=======본문======= \n", content.text.strip()) ws[f'A{row}'] = url # A열에는 URL 기입 ws[f'B{row}'] = title.text.strip() ws[f'C{row}'] = content.text.strip() # 자동 줄바꿈 ws[f'C{row}'].alignment = Alignment(wrap_text=True) row = row + 1 time.sleep(0.3) # 마지막 페이지 여부 확인하기 isLastPage = soup.select_one("a.btn_next").attrs['aria-disabled'] if isLastPage == 'true': print("마지막 페이지 입니다.") break page_num = page_num + 1 wb.save(f'{keyword}_result.xlsx')
-
미해결이것이 진짜 크롤링이다 - 실전편
크롤링 기사 기간 설정
안녕하세요뉴스크롤링에서 크롤링 하고자 하는 뉴스의 기간을 정해주려면response = requests.get("https://search.naver.com/search.naver?where=news&sm=tab_jum&query=검색어") 위 코드의 " " 안에 뉴스기간을 옵션으로 설정하여 검색한 페이지의 URL을 긁어서 넣어주면 되는걸지요? 감사합니다.
-
미해결이것이 진짜 크롤링이다 - 실전편
코드가 작동이 되었다가 다시 안되는데요 ㅠㅠ
분명히 작동을 잘 했었는데,제가 어디서 잘못을 한것인지 아래와 같은 에러가 반복해서 발생합니다.startcoding/Chapter04/11.마지막페이지확인하기.py", line 62, in <module>print("=======링크======= \n", url)^^^NameError: name 'url' is not defined 강의를 뒤로가서 다시 작성해봐도... 이제는 02.본문내용스크롤부터 에러가 발생하고, Chapter04/02.뉴스본문내용크롤링하기.py", line 17, in <module>print(content.text)^^^^^^^^^^^^AttributeError: 'NoneType' object has no attribute 'text'"10.크롤링결과엑셀저장하기"에서도 돌아가다가 2페이지부터 이런 에러가 발생합니다. startcoding/Chapter04/10.크롤링결과엑셀저장하기.py", line 63, in <module> print("=======제목======= \n", title.text.strip()) ^^^^^^^^^^AttributeError: 'NoneType' object has no attribute 'text'제가 도대체 어디를 잘못하고 있는 걸까요 ㅠㅠ import requestsfrom bs4 import BeautifulSoupimport time # Time module 불러오기import pyautoguifrom openpyxl import Workbookfrom openpyxl.styles import Alignment# 사용자입력푸드keyword = pyautogui.prompt("검색어를 입력하세요")lastpage = int(pyautogui.prompt("몇 페이지까지 크롤링 할까요?"))# 엑셀 생성하기wb = Workbook()# 엑셀 시트 생성하기ws = wb.create_sheet(keyword)# 열 너비 조절ws.column_dimensions['A'].width = 60ws.column_dimensions['B'].width = 60ws.column_dimensions['C'].width = 120# 행번호row = 1# 페이지번호page_num = 1for i in range(1, lastpage * 10, 10):print(f"{page_num}페이지 크롤링 중입니다.===============")response = requests.get(f"https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query={keyword}&start={i}")html = response.textsoup = BeautifulSoup(html, 'html.parser')articles = soup.select("div.info_group") # 뉴스 기사 div 10개 추출(ctrl+F, div.info_group 검색후 10개로 확인)for article in articles:links = article.select("a.info") # 리스트: a 태그인데, class가 info인 것들 가지고 오기if len(links) >= 2: # 링크가 2개 이상이면url = links[1].attrs['href'] # 두번째 링크의 href를 추출response = requests.get(url, headers={'User-agent':'Mozila/5.0'})html = response.textsoup = BeautifulSoup(html, 'html.parser')# 연예 뉴스 체크if "entertain" in response.url:title = soup.select_one(".end_tit")content = soup.select_one("#articeBody")elif "sports" in response.url:title = soup.select_one("h4.title")content = soup.select_one("#newsEndContents")# 본문 내용 안에 불필요한 div 삭제 (기사 본문 이후 내용들)divs = content.select("div")for div in divs:div.decompose()paragraphs = content.select("p")for p in paragraphs:p.decompose()else:title = soup.select_one(".media_end_head_headline")content = soup.select_one("#newsct_article")print("=======링크======= \n", url)print("=======제목======= \n", title.text.strip())print("=======본문======= \n", content.text.strip())ws[f'A{row}'] = urlws[f'B{row}'] = title.text.strip()ws[f'C{row}'] = content.text.strip()# 자동 줄바꿈ws[f'C{row}'].alignment = Alignment(wrap_text=True)row = row + 1time.sleep(0.3) # 프로그램을 0.3초 정도 휴식 주기 (서버 부담 줄여주기, 프로그램 안정성 up)page_num = page_num + 1wb.save(f'{keyword}_result.xlsx')
-
미해결파이썬입문과 크롤링기초 부트캠프 [파이썬, 웹, 데이터 이해 기본까지] (업데이트)
뉴스 기사 크롤
위 페이지에서 기사 제목: 김혜수 "실패 없을 것 같은 내 이력..."<span class="text">를 출력하고자 합니다. select를 이용해서 출력하고자 하는데, 어떤 것이 잘못되었는지 모르겠습니다. items = soup.select('ol#topViewArticlesContainer p.title span.text') ol id가 topViewArticlesContainer 밑에p 태그의 class가 title인 것의 밑에span 태그의 class가 text인 것을 뽑으려고 했는데,, 어떤게 잘못 된건지 알 수 있을까요?
-
미해결이것이 진짜 크롤링이다 - 실전편
임포트가 잘 안되요~~~~
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.