본문 바로가기

🥾 프로젝트/(인프런)파이썬 텍스트 분석 입문 - 데이터 수집부터 분석까지

1. 크롤링

URL 불러오기(params)

url = "https://www.yna.co.kr/search/index"
params = {
    "query":"경제", 
    "from":"20191102", 
    "to":"20201102", 
    "period":"1y"
}
r = requests.get(url, params=params)
url = "https://www.yna.co.kr/search/index"

# 위와 동일
url = "https://www.yna.co.kr/search/index?query=경제&from=20191102&to=20201102&period=1y"

1. 규칙성을 파악 후에 params을 사용해 조금 더 쉽게 크롤링을 한다.

URL 불러오기(header)

url = "https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending"

# headers={"user-agent":"myBot"}
r = requests.get(url, headers=None)

from bs4 import BeautifulSoup
print(BeautifulSoup(r.text).find(attrs={"class":"table-striped"}).text)

1. 사이트마다 가끔 python을 막아두는 경우가 있음(python이 느리기 때문에)

2. header를 통해 사용자가 임의로 변경해서 url를 불러오는 방법.

Encoding

import requests

url = "https://www.yna.co.kr/view/AKR20201012029200063?section=society/all"
r = requests.get(url)

print(r.encoding)
#결과 : UTF-8

r.text
#결과 : ~문서 전체 출력

1. r.text는 우리가 보는 문자열로 반환.

2. r.content는 r.text 이전 단계이며, byte문자로 보여줌.  (x97\xb0\xed\x95..)

Encoding(폰트 깨짐 해결)

r.encoding = 'EUC-KR' #  or 'euk-kr'
r.text[1000:2000]

1. 위와 같은 방법으로 한글 폰트 깨짐을 해결할 수 있음.

HTML 파일이 아닌 경우(CSV) 깔끔하게 보는 방법

  1. DataFrame 이용
  2. read.csv 이용
  3. io.StringIO 이용

BeautifulSoup

r = requests.get("https://ko.wikipedia.org/wiki/%EC%9C%84%ED%82%A4%EB%B0%B1%EA%B3%BC:%EB%8C%80%EB%AC%B8")

# 문자열을 BeautifulSoup 객체로 만들기
from bs4 import BeautifulSoup

soup = BeautifulSoup(r.text)

# 타입이 BeautifulSoup임 -> str형태로 변환 예정
type(soup)

# prettify :
# 1. 들어쓰기 역할을 하면서 보기 좋게 해줌
# 2. 문자형으로 변환
print(soup.prettify())

# 여기서 여러가지 title, div 등 검색이 가능함.
soup = BeautifulSoup(soup.prettify())
soup

1. prettify : 글을 이쁘게 보여주며, str 형태로 변환해줌.

태그 속성을 이용한 검색

print(soup.find(attrs={"class":"firstHeading"}))

#결과
#<h1 class="firstHeading" id="firstHeading" lang="en">Natural language processing</h1>
content_texts = soup.find(attrs={"class":"mw-parser-output"})

content_ls = []
for content in content_texts.find_all("p")[:2]:
    content_ls.append(content.text)
    
print("\n".join(content_ls))

#결과
Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data.

Challenges in natural language processing frequently involve speech recognition, natural language understanding, and natural-language generation.

링크 추출하기 (공부 더 필요)

for tag in soup.find_all('a'):
    if 'href' in tag.attrs:
        if tag['href'].startswith('/wiki/'):
            print(tag['href'])

위키피디아 여러 페이지 방문하면서 데이터 수집하는 코드 (공부 더 필요)

import requests
from bs4 import BeautifulSoup 
import pandas as pd

def parse_title(soup):
    return soup.find(attrs={"id":"firstHeading"}).text

def parse_content(soup):
    tags = soup.find(attrs={"class":"mw-parser-output"}).find_all("p")
    contents = [tag.text for tag in tags]
    return ' '.join(contents).strip()
    
def parse_url(soup):
    urls = []
    for tag in soup.find_all('a'):
        if 'href' in tag.attrs:
            href = tag['href']
            if href.startswith('/wiki/') and ':' not in href:
                if "https://en.wikipedia.org"+href not in urls:
                    urls.append("https://en.wikipedia.org"+href)
    return urls

# 초기 URL requests
SEARCHING_WORDS = "Natural_language_processing"

queue = [f"https://en.wikipedia.org/wiki/{SEARCHING_WORDS}"]
data = []
i = 0
while queue:
    # 요청 보내기
    url = queue.pop(0)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, "html.parser")

    # 정보 추출하기
    title = parse_title(soup)
    content = parse_content(soup)
    data.append((title, content))
    queue.extend(parse_url(soup))
    
    i += 1
    if i > 5:
        break

1. 아래는 위키피디아의 여러 페이지를 방문하면서 데이터를 수집하는 코드입니다.

  • parse_title: 제목을 수집합니다.
  • parse_content: 본문을 수집합니다.
  • parse_url: 링크를 수집합니다.

SEARCHING_WORDS에 검색하고자 하는 단어를 넣은 뒤 실행시키면, 해당 페이지를 검색하고, 해당 페이지에 걸려있는 링크를 타고 넘어가 다시 데이터를 수집하는 것을 반복합니다.