- [python] Beautifulsoup 네이버 뉴스 크롤링 2020.05.27
- [python] 파이썬 네이버 크롤링 하여 csv 파일로 2020.05.25
https://bumcrush.tistory.com/116
크롤링을 하다보니 "태그위치 달라지는" 날짜를 얻어오는 것에 대해 방법을 찾다가 위의 글을 찾게 되었습니다.
<크롤링 할 내용>
-
1. 기사 - title
-
2. 신문사 - newspaper
-
3. 날짜 - date
-
4. 내용 요약 - content
-
5. 링크 - link
1. 크롤링을 위한 라이브러리
설치 방법
외부 라이브러리
1) Beautifulsoup - 태그 접근
CMD - 'python -m pip install bs4' 입력 ('제외)
2) pandas (엑셀로 저장할 때) or python-docx(워드로 저장)
CMD - 'python -m pip install pandas'
CMD - 'python -m pip install python-docx'
내부 라이브러리
1) datetime - 저장파일을 시간으로 저장하기 위해서
2) requests - 웹 요청
3) re - 정규식
2. 크롤링을 하려면 html 태그를 알아야하며, 태그의 속성 (href, class, title...) 같은 속성이 필요
크롬도구(F12) -> 빨간 네모 부분 클릭 -> 가져올 기사 Title에 포커스를 두고 클릭 -> 해당하는 부분이 바로 찾아짐
3. html 코드는 아래 처럼 많은 태그들로 이루어 져있고, 아래의 a 태그에는 href, target, class 등과 같은 속성과 strong 태그도 존재
<a href="https://www.zdnet.co.kr/view/?no=20200526125336"
target="_blank"
class=" _sp_each_title"
onclick="return goOtherCR(this, 'a=nws*a.tit&r=1&i=8800011E_000000000000000002189487&g=092.0002189487&u='+urlencode(this.href));"
title="유아이패스, 27일 RPA 세미나 개최">
유아이패스, 27일
<strong class="hl">RPA</strong>
세미나 개최
</a>
4. 검색 파라미터 url 분석
#1일 이내 (현재시간으로부터)
https://search.naver.com/search.naver?&where=news
&query=RPA
&sm=tab_pge
&sort=1
&photo=0
&field=0
&reporter_article=
&pd=4
&ds=2020.05.26.13.23
&de=2020.05.27.13.23
&docid=
&nso=so:dd,p:1d,a:all
&mynews=0
&start=1
&refresh_start=0
#1주일
https://search.naver.com/search.naver?&where=news
&query=RPA
&sm=tab_pge
&sort=1
&photo=0
&field=0
&reporter_article=
&pd=1
&ds=2020.05.20
&de=2020.05.27
&docid=
&nso=so:dd,p:1w,a:all
&mynews=0
&start=1
&refresh_start=0
필터를 넣어서 검색을 해보면 위와 같은 url을 볼 수 있다.
특징을 살펴보자.
- &query= "검색값"
- &sm="tab_pge" 이 값은 검색했을 때 "tab_opt"로 나오고, 페이지를 한번 2페이지로 옴겼다가 1페이지로 돌아오면 됨
- &sort="정렬 방식" 1일 때 최신순
- &pd= "period"의 pd로 생각 된다.
- 필터를 조절하며, 값을 다르게 주었더니 다음과 같은 결과를 얻었다.
&pd =
- '1일 이내'='4',
- '1주이내'='1',
- '1개월 이내' = '2',
- '6개월 이내' = '6',
- '1년 이내' = '5',
- '선택기간' = '3'
&ds= 기간이며, 1일 이내의 시간에 대해서는 2020.05.27.'tt'.'mm' 으로 표시되며, 기준은 현재시간
'Python' 카테고리의 다른 글
[python] 파이썬 네이버 크롤링 하여 csv 파일로 (0) | 2020.05.25 |
---|
from urllib.request import urlopen
from urllib.parse import quote_plus
from bs4 import BeautifulSoup
import pandas as pd
pageNum = 1
search = input('검색어: ')
page = input('끝 페이지 입력')
lastpage = int(page) * 10 -9
searchlist = []
while pageNum < lastpage + 1:
url = f'https://search.naver.com/search.naver?&where=news&query={quote_plus(search)}&sm=tab_pge&sort=0&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid=&nso=so:r,p:all,a:all&mynews=0&cluster_rank=37&start=1&refresh_start={pageNum}'
html = urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
title = soup.find_all(class_='_sp_each_title')
for i in title :
print(i.attrs['title'])
print(i.attrs['href'])
print(pageNum)
temp = []
temp.append(i.attrs['title'])
temp.append(i.attrs['href'])
searchlist.append(temp)
searchfile = pd.DataFrame(searchlist)
pageNum += 10
searchfile.to_csv('naver.csv', encoding = 'CP949', index = False, header = ['제목' , '기사 url'])
'Python' 카테고리의 다른 글
[python] Beautifulsoup 네이버 뉴스 크롤링 (0) | 2020.05.27 |
---|