logo

Python Web Scraping을 사용하여 선택한 웹페이지 콘텐츠 읽기

전제 조건: Python에서 파일 다운로드 BeautifulSoup을 사용한 웹 스크래핑 우리 모두는 Python이 매우 쉬운 프로그래밍 언어라는 것을 알고 있습니다. 그러나 Python을 더욱 멋지게 만드는 것은 이를 위해 작성된 수많은 오픈 소스 라이브러리입니다. Requests는 가장 널리 사용되는 라이브러리 중 하나입니다. 이를 통해 우리는 HTTP/HTTPS 웹사이트를 열 수 있고 일반적으로 웹에서 수행하는 모든 종류의 작업을 수행할 수 있으며 세션(예: 쿠키)을 저장할 수도 있습니다. 우리 모두는 웹페이지가 웹 서버에서 브라우저로 전송되어 아름다운 페이지로 변환되는 HTML 코드일 뿐이라는 것을 알고 있습니다. 이제 HTML 소스 코드를 확보하는 메커니즘, 즉 BeautifulSoup이라는 패키지로 특정 태그를 찾는 메커니즘이 필요합니다. 설치:
pip3 install requests 
pip3 install beautifulsoup4 

뉴스 사이트를 읽음으로써 예를 들어 보겠습니다. 힌두스탄 타임즈

코드는 세 부분으로 나눌 수 있습니다.
  • 웹페이지 요청
  • 태그 검사
  • 적절한 내용을 인쇄하세요.
단계:
    웹페이지 요청:먼저 뉴스 텍스트를 마우스 오른쪽 버튼으로 클릭하여 소스 코드를 확인합니다. Python Web Scraping을 사용하여 선택한 웹페이지 콘텐츠 읽기' title= 태그 검사:우리는 스크랩하려는 뉴스 섹션이 포함된 소스 코드 본문을 파악해야 합니다. 이는 뉴스 섹션을 포함하는 uli.e 정렬되지 않은 목록 'searchNews'입니다. Python Web Scraping을 사용하여 선택한 웹페이지 콘텐츠 읽기' title= 참고 뉴스 텍스트는 앵커 태그 텍스트 부분에 있습니다. 자세히 관찰해 보면 모든 뉴스가 순서가 지정되지 않은 태그의 li 목록 태그에 있다는 아이디어를 얻을 수 있습니다. Python Web Scraping을 사용하여 선택한 웹페이지 콘텐츠 읽기' title= 적절한 내용을 인쇄하십시오: The content is printed with the help of code given below. Python
    import requests from bs4 import BeautifulSoup def news(): # the target we want to open  url='http://www.hindustantimes.com/top-news' #open with GET method resp=requests.get(url) #http_respone 200 means OK status if resp.status_code==200: print('Successfully opened the web page') print('The news are as follow :-n') # we need a parserPython built-in HTML parser is enough . soup=BeautifulSoup(resp.text'html.parser') # l is the list which contains all the text i.e news  l=soup.find('ul'{'class':'searchNews'}) #now we want to print only the text part of the anchor. #find all the elements of a i.e anchor for i in l.findAll('a'): print(i.text) else: print('Error') news() 

    산출

    Successfully opened the web page The news are as follow :- Govt extends toll tax suspension use of old notes for utility bills extended till Nov 14 Modi Abe seal historic civil nuclear pact: What it means for India Rahul queues up at bank says it is to show solidarity with common man IS kills over 60 in Mosul victims dressed in orange and marked 'traitors' Rock On 2 review: Farhan Akhtar Arjun Rampal's band hasn't lost its magic Rumours of shortage in salt supply spark panic among consumers in UP Worrying truth: India ranks first in pneumonia diarrhoea deaths among kids To hell with romance here's why being single is the coolest way to be India vs England: Cheteshwar Pujara Murali Vijay make merry with tons in Rajkot Akshay-Bhumi SRK-Alia Ajay-Parineeti: Age difference doesn't matter anymore Currency ban: Only one-third have bank access; NE backward regions worst hit Nepal's central bank halts transactions with Rs 500 Rs 1000 Indian notes Political upheaval in Punjab after SC tells it to share Sutlej water Let's not kid ourselves with Trump what we have seen is what we will get Want to colour your hair? Try rose gold the hottest hair trend this winter 

참고자료



퀴즈 만들기