주소창에 sports가 들어가 있어도 읽어서 출력해요ㅠㅠ
240
작성한 질문수 2
import requests
from bs4 import BeautifulSoup
import time
response = requests.get('https://search.naver.com/search.naver?ssc=tab.news.all&where=news&sm=tab_jum&query=%EC%86%90%ED%9D%A5%EB%AF%BC')
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 : # 링크가 2개 이상이면
url = links[1].attrs['href'] # 두번째 링크의 href를 추출
# 다시 request 날려 준다
response = requests.get(url, headers={'User-agent':'Mozila/5.0'})
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")
# 본문 내용안에 불필요한 div, p 삭제
divs = content.select('div')
for div in divs :
div.decompose()
paragrahs = content.select('p')
for p in paragrahs:
p.decompose()
else :
title = soup.select_one(".media_end_head_headline")
content = soup.select_one("#newsEndContents")
print("==========링크==========\n", url)
print("==========제목==========\n", title.text.strip())
print("==========본문==========\n", content.text.strip())
time.sleep(0.3)==========링크==========
https://n.news.naver.com/mnews/article/005/0001678573?sid=102
==========제목==========
나이도 못 막았다… 8090 ‘은발의 손흥민’들
Traceback (most recent call last):
File "c:\Program Files\FirstPython\crawling\10.셀리니움_기본설정\Chapter04\04.스포츠뉴스크롤링하기.py", line 42, in <module>
print("==========본문==========\n", content.text.strip())
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'text'
하면 이렇게 에러가 나요 선생님 ㅠ.ㅠ 주소창을 보니깐 sports가 안 들어가 있는데 출력이 되어서 나옵니다. 혹시 넘어갈려면 어떻게 해야 하는지 여쭤봐도 되겠습니까?!
답변 1
1
안녕하세요!!
HTML에서 약간 업데이트가 있었네요
연예, 스포츠 뉴스가 아닌 일반뉴스의 본문을 가져오려면 선택자를 다음과 같이 써야 합니다
<CSS Selector>
#dic_area
import requests
from bs4 import BeautifulSoup
import time
response = requests.get('https://search.naver.com/search.naver?ssc=tab.news.all&where=news&sm=tab_jum&query=%EC%86%90%ED%9D%A5%EB%AF%BC')
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 : # 링크가 2개 이상이면
url = links[1].attrs['href'] # 두번째 링크의 href를 추출
# 다시 request 날려 준다
response = requests.get(url, headers={'User-agent':'Mozila/5.0'})
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")
# 본문 내용안에 불필요한 div, p 삭제
divs = content.select('div')
for div in divs :
div.decompose()
paragrahs = content.select('p')
for p in paragrahs:
p.decompose()
else :
title = soup.select_one(".media_end_head_headline")
content = soup.select_one("#dic_area")
print("==========링크==========\n", url)
print("==========제목==========\n", title.text.strip())
print("==========본문==========\n", content.text.strip())
time.sleep(0.3)
셀레니움 환경설정 오류
0
61
2
네이버 로그인 관련
0
293
2
안녕하세요 셀레니움에 대해서 질문
0
94
1
크롤링 연습사이트 문의
0
109
2
선택자 질문
0
82
2
'특정 요소가 나타날 때까지 스크롤' 부분 에러
0
85
2
자동 로그인 질문
0
97
2
44강 제목, 링크
0
108
1
원하는 값이 없을 때
0
96
2
크롤링한 링크가 엑셀로 들어가면 작동이 안되요
0
234
2
셀레니움 PDF자료는 받을 수 있나요
0
103
2
글목록 추출하기
0
104
2
메일 자동화 로그인 중복방지문자해결 오류 및 명시적 대기 질문
0
93
2
강의 노트가 어디에 있는건가요?
0
81
2
강의 커리큘럼 질문
0
104
1
조건문 else 사용하지 않는 이유
0
79
2
셀레니움으로 접근할 수 없는 경우
0
100
2
웹페이지 변경
0
76
2
자바스크립트로 태그 선택 시 질문입니다.
1
67
2
수료증은 어떻게 받나요?
0
123
2
class명을 활용하여 선택자를 만들지 않는 경우..?
0
64
2
드라이버가 안 열려요
0
83
2
이거 해결방법 아시는 분?
0
123
2
네이버 지식인 크롤링..
0
207
2





