NLP/STUDY

[DAY 5] Python: Lecture 13. Web

욤미 2022. 11. 7. 12:42
728x90
반응형

[Lecture 13] Web

Web Page

  • 서버에 요청을 보내면 서버는 리소스를 사용자에게 보여줌 웹 브라우저를 통해 포맷팅 되어 화면에 나타난다.
  • html은 xml 구조를 가진다. → F12키로 Development Tool 확인 가능
  • html을 가져와서 beautiful soup 등 xml parser로 해석 가능

Requests

  • 웹페이지를 읽기 위한 라이브러리
  • conda install requests
import requests

url = '<https://www.naver.com>'
response = requests.get(url) # GET으로 접근

print(response.status_code) # 결과 코드, 200 정상 제대로 데이터를 가져옴/ 404 웹페이지를 찾을 수 없다. / 500 웹 서버에 문제가 있다.
print(response.text)

Crawling

  • 오늘자 네이버 스포츠 뉴스 기사 제목 크롤링 하기
    • ul 태그 안에서 strong 태그 가져오기
import requests
from bs4 import BeautifulSoup

url = '<https://sports.news.naver.com/index>' # 네이버 스포츠 뉴스
response = requests.get(url) # GET으로 접근

with open('test.xml', 'r') as f:
	soup = BeautifulSoup(
		f.read(),    # 파싱할 문자열
		'html.parser' # 사용할 파서
)

headline = soup.find(name='ul', atts={'class': 'today_list'})
for title in headline.find_all(name='strong', attrs={'class': 'title'}):
	print(title.string)

클릭해서 파싱하고 하는 건 Scrapy가 유용함

 

추가로 학습하면 좋은 부분들

  1. Multi Processing/Multi Thread
  2. Networking
728x90
반응형