import requests
from lxml import html

url="<http://news.naver.com>"

headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.118 Whale/2.11.126.23 Safari/537.36'}
html_req=requests.get(url,headers=headers)
#html_req: 가져올 문서를 저장할 변수
#requests.get
#url: 웹페이지 주소
#headers=headers: 통신할 때 전달할 바로 위에서 저장한 headers 값을 headers 라는 속성에 저장
#cf)post 방식으로 통신할 때는 headers 외에 추가로 data 라는 속성이 필요하기도 함

tree=html.fromstring(html_req.content)
#tree: 가져온 문서를 html 형태로 해석한 뒤 저장할 변수
#html.fromstring: 문서의 내용을 html구조로 해석
#html_req.content: encoding하지 않은 상태의 수집 문서

titles=tree.xpath('//div[@class="hdline_article_tit"]/a/text()')
#titles: 뉴스 제목 부분을 추출한 목록을 저장한 변수 (list형으로 자동 설정됨)
#tree.xpath: tree 내용중에서 괄호에 있는 내용에 맞는 부분을 추출 (xpath 규칙을 따르는 것)
#괄호내용: 뉴스 제목에 해당하는 부분을 추출하는 xpath 문법

print(titles)

results=[]

for title in titles:
    title_clean=title.replace("\\n"," ").replace("\\t"," ").replace("\\r"," ").strip()
    results.append(title_clean)

⭐get, post 방식

[출처] 삼성 멀티캠퍼스 파이썬 교육 6일차(0710)/ POST,GET 방식|작성자 ysw01044

[출처] [파이썬] 크롤링 기초 : requests 모듈 (GET, POST)|작성자 꼬꼬떡국

⭐html_req.content, .text

-html_req.content: encoding 하지 않은 상태의 수집 문서

-html_req.text: 자동으로 encoding 한 결과

-.text가 편리할 수 있으나, encoding 오류가 발생할 수 있기 때문에, .content 사용이 일반적임

⭐xpath 문법 기초(1)

Untitled

Untitled

커서는 올려둔 뒤 오른쪽 버튼 - 검사