1. 페이지 XPath
"""
최신 30개의 뉴스 기사 본문을 크롤링하는 것.
- 팁
1. 페이지 버튼 클릭
10번째 뉴스 기사 아래에 보면 페이지 버튼 10개가 있습니다.
1페이지는 이미 접속되어 있으므로, 2페이지와 3페이지만 다뤄주면 되겠죠!
2페이지 버튼과 3페이지 버튼의 XPath를 확인해보시면, 어떤 패턴을 발견할 수 있습니다.
반복문을 통해 이 패턴을 활용하면, 2페이지 버튼과 3페이지 버튼을 순서대로 자동 클릭해주는 코드를 구현할 수 있겠죠??
"""
from selenium import webdriver
import time
keyword = input('뉴스 검색 키워드 : ')
driver = webdriver.Chrome('./chromedriver')
news_url = 'https://search.hankyung.com/apps.frm/search.news?query=' + keyword + '&mediaid_clust=HKPAPER,HKCOM'
driver.get(news_url)
time.sleep(2)
# 1번 페이지 XPath > //*[@id="content"]/div[1]/div[2]/div[2]/div/span/strong
# 2번 페이지 XPath > //*[@id="content"]/div[1]/div[2]/div[2]/div/span/a[1]
# 3번 페이지 XPath > //*[@id="content"]/div[1]/div[2]/div[2]/div/span/a[2]
XPath_list = ['strong', 'a[1]', 'a[2]']
count = 0
for page_xpath in XPath_list:
driver.find_element_by_xpath(f'//*[@id="content"]/div[1]/div[2]/div[2]/div/span/{page_xpath}').click()
ten_articles = driver.find_elements_by_css_selector('em.tit')
for article in ten_articles:
title = article.text
article.click()
time.sleep(1)
driver.switch_to.window(driver.window_handles[-1])
try:
content = driver.find_element_by_id('articletxt').text
seperate = content.split('\n')
count += 1
print(f'< {count}번 뉴스 - {title} >')
for sep in seperate:
if sep != '':
print(sep, end=' ')
except:
count += 1
print(f'< {count}번 뉴스 - {title} >')
print('id 요소가 다릅니다.')
print('\n')
driver.close()
driver.switch_to_window(driver.window_handles[0])
time.sleep(1)
driver.close()
>> 결과
2. 페이제 url
"""
최신 30개의 뉴스 기사 본문을 크롤링하는 것.
- 팁
2. url 주소
1~3페이지의 url 주소 패턴을 활용하면 쉽게 구현할 수 있겠네요!
"""
from selenium import webdriver
import time
keyword = input('뉴스 검색 키워드 : ')
driver = webdriver.Chrome('./chromedriver')
news_url = 'https://search.hankyung.com/apps.frm/search.news?query=' + keyword + '&mediaid_clust=HKPAPER,HKCOM'
count = 0
for page_num in range(1,4):
page_url = news_url + f'&page={page_num}'
driver.get(page_url)
time.sleep(2)
ten_articles = driver.find_elements_by_css_selector('em.tit')
for article in ten_articles:
title = article.text
article.click()
time.sleep(1)
driver.switch_to.window(driver.window_handles[-1])
try:
content = driver.find_element_by_id('articletxt').text
seperate = content.split('\n')
count += 1
print(f'< {count}번 뉴스 - {title} >')
for sep in seperate:
if sep != '':
print(sep, end=' ')
except:
count += 1
print(f'< {count}번 뉴스 - {title} >')
print('id 요소가 다릅니다.')
print('\n')
driver.close()
driver.switch_to_window(driver.window_handles[0])
time.sleep(1)
driver.close()
'코린이_탈출 > 크롤링' 카테고리의 다른 글
[모각코_크롤링] 동적 크롤링 5 (0) | 2021.01.29 |
---|---|
[모각코_크롤링] 동적 크롤링 4-과제 (1) | 2021.01.28 |
[모각코_크롤링] 동적 크롤링 4 (0) | 2021.01.28 |
[모각코_크롤링] 동적 크롤링 3 - 과제 (1) | 2021.01.27 |
[모각코_크롤링] 동적 크롤링 3 (0) | 2021.01.27 |