본문 바로가기

:: System Log

파이썬 2단계 크롤링입문

[ 파이썬 크롤링 입문 ]
 
# Body 꾸미기

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>엘리스 :: elice</title>
  </head>
  <body>
    <h1>네이버와 엘리스로 연결되는 링크 만들기</h1>
    <!-- 아래 코드를 완성하고 제출 버튼을 눌러보세요! -->
    <h2>네이버로 가는 링크</h2>
    <p>네이버 메인 페이지로 가는 링크입니다.</p>
    네이버
    <h2>엘리스로 가는 링크</h2>
    <p>엘리스 아카데미로 가는 링크입니다. 엘리스 로고를 클릭해주세요!</p>
   
        <img src="elice_logo.png" alt="엘리스 회사 로고" />
    </a>
  </body>
</html>

 
#구역설정 및 여러 요소 한꺼번에 꾸미기

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>엘리스 :: elice</title>
  </head>
  <body>
    <!-- 아래 코드를 완성하고 제출 버튼을 눌러보세요! -->
    <div style ="color:blue">
        <p>첫째 줄</p>
        <p>둘째 줄</p>
        <div style = "font-size:2em">
            <p>셋째 줄</p>
            <p><span style ="color:red">넷째</span> 줄</p>
        </div>
    </div>   
  </body>
</html>

 
#전역 속성 적용하기

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <style>
      .frame {
        background-color: yellow;
        border: 5px outset red;
        padding: 5px;
      }
      .center {
        text-align: center;
      }
    </style>
    <title>엘리스 :: elice</title>
  </head>
  <body>
    <!-- 아래 코드를 완성하고 제출 버튼을 눌러보세요! -->
   <h1 class="center">엘리스</h1>
    <div class="frame center">
      <img src="elice_logo.png" title="엘리스 로고" alt="elice logo"  />
      <p hidden>엘리스 로고</p>
    </div>
  </body>
</html>

 
#태그 이름으로 요소 찾기

from selenium import webdriver
# 지시사항 1번을 작성하세요.
with webdriver.Firefox() as driver:
   
    # 지시사항 2번을 작성하세요.
    driver.get('http://localhost:8080')
    # 지시사항 3번을 작성하세요.
    e = driver.find_element_by_tag_name('title')
    print(e.text)
    # 지시사항 4번을 작성하세요.
   e_list = driver.find_elements_by_tag_name('img')
    for i in e_list :
        print(i.get_attribute("src"))
    # 지시사항 5번을 작성하세요.
   p_list = driver.find_elements_by_tag_name('div')
    for p in p_list :
        print(p.text)
   

 
#다양한 방법으로 요소찾기

from selenium import webdriver
# 지시사항 1번을 작성하세요.
with webdriver.Firefox() as driver :
    driver.get('http://localhost:8080')
    # 지시사항 2번을 작성하세요.
    ol_list = driver.find_element_by_tag_name('ol')
    li_list = ol_list.find_elements_by_tag_name('li')
    for li in li_list :
            print(li.text)
        # 지시사항 3번을 작성하세요.
    bic_list = driver.find_elements_by_class_name('big')
    for bic in bic_list :
        print(bic.text)
    # 지시사항 4번을 작성하세요.
    ul = driver.find_element_by_tag_name('ul')
    bld = ul.find_element_by_class_name('bold')
    print(bld.text)
   

 
#XPath로 요소 찾기

from selenium import webdriver
# 지시사항 1번을 작성하세요.
with webdriver.Firefox() as driver :
    driver.get("http://localhost:8080")
    # 지시사항 2번을 작성하세요.
    xpath = '//ol/li'
    print(xpath)
    # 지시사항 3번을 작성하세요.
    x_list = driver.find_elements_by_xpath(xpath)
    for x in x_list:
        print(x.text)
    # 지시사항 4번을 작성하세요.
    xpath2 =  '//*[contains(@class, "big")]'
    print(xpath2)
    # 지시사항 5번을 작성하세요.
    x_list2 = driver.find_elements_by_xpath(xpath2)
    for x in x_list2:
        print(x.text)
    # 지시사항 6번을 작성하세요.
    xpath3 = '//ul/*[@class=\'bold\']'
    print(xpath3)
    # 지시사항 7번을 작성하세요.
    x_list3 = driver.find_elements_by_xpath(xpath3)
    for x in x_list3:
        print(x.text)

 
 
#웹페이지 로딩 기다리기

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
with webdriver.Firefox() as driver:
    driver.get("http://localhost:8080")
    # 지시사항 1번을 작성하세요.
    try:
        e = driver.find_element_by_tag_name('img')
        print(e.get_attribute("src"))
    except Exception:
        print("아직 요소가 불러와지지 않았습니다.")
    driver.get("http://localhost:8080")
    # 지시사항 2번을 작성하세요.
    time.sleep(10)
    try:
       e =  driver.find_element_by_tag_name('img')
       print(e.get_attribute("src"))
    except Exception:
        print("아직 요소가 불러와지지 않았습니다.")
    driver.get("http://localhost:8080")
    # 지시사항 3번을 작성하세요.
    driver.implicitly_wait(10)
    try:
        e =  driver.find_element_by_tag_name('img')
        print(e.get_attribute("src"))
    except Exception:
        print("아직 요소가 불러와지지 않았습니다.")
with webdriver.Firefox() as driver:
    driver.get("http://localhost:8080")
 
    # 지시사항 4번을 작성하세요.
    e = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located(
            (By.TAG_NAME, "img")))
    print(e.get_attribute("src"))
    try:
        pass
    except Exception:
        print("아직 요소가 불러와지지 않았습니다.")

 
#키보드/마우스 입력

from selenium import webdriver
with webdriver.Firefox() as driver:
    driver.get("http://localhost:8080")
    input_id = input()
    input_pw = input()
   
    # 지시사항 1번과 2번을 작성하세요.
   e = driver.find_element_by_id('id')
    e.send_keys(input_id)
    # 지시사항 3번을 작성하세요.
    p = driver.find_element_by_id('pw')
    p.send_keys(input_pw)
   
    # 지시사항 4번을 작성하세요.
    button = driver.find_element_by_id('login')
    button.click()
    # 지시사항 5번을 작성하세요.
    m = driver.find_element_by_id('message')
    print(m.text)

#ActionChains의 활용

from selenium import webdriver
with webdriver.Firefox() as driver:
    driver.get("http://localhost:8080")
    input_id = input()
    input_pw = input()
 
    # 지시사항 1번을 작성하세요.
    id_e = driver.find_element_by_id('id')
    pw_e = driver.find_element_by_id('pw')
    login_e = driver.find_element_by_id('login')
 
    # 지시사항 2번을 작성하세요.
    chains = webdriver.ActionChains(driver)
   
    # 지시사항 3번을 작성하세요.
    chains.send_keys_to_element(id_e, input_id)
    chains.send_keys_to_element(pw_e, input_pw)
   
    # 지시사항 4번을 작성하세요.
    chains.click(login_e)
    # 지시사항 5번을 작성하세요.
    chains.perform()
    m_e = driver.find_element_by_id('message')
    print(m_e.text)   

 
#명언태그 수집

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def crawl_contents(driver, url):
    # 명언들의 태그의 빈도를 담고 있는 딕셔너리를 반환하세요.
    tags = {}
    allTags = [] #전체태그리스트 - 갯수세기용
    tagVal = [] #중복제거
    driver.get(url)
 
    tagcl = driver.find_elements_by_xpath('//*[@class=\'tags\']/*[@class=\'tag\']')
    for t in tagcl :
        allTags.append(t.text)
 
    tagVal = list(set(allTags))
 
    for tag in tagVal :
        tags[tag] = allTags.count(tag)
    return tags
 
def main():
    # 브라우저 web driver 설정(Firefox)
    options = FirefoxOptions()
    with webdriver.Firefox(options=options) as driver:
        # 데이터를 가져올 사이트의 URL
        url = "http://quotes.toscrape.com/"
        print(crawl_contents(driver, url))
if __name__ == "__main__":
    main()

 
파이썬으로 시작하는 데이터 분석
 
#퀴즈_다음과 같은 데이터 프레임에서 도도새의 점수를 95점으로바꾸는 코드로 알맞은 것은?
df.loc[“도도새”, “점수”] =95
 
 
# 이어붙이고 나누기
——
import numpy as np
print("matrix")
matrix = np.array([[ 0, 1, 2, 3],
                   [ 4, 5, 6, 7],
                   [ 8, 9,10,11],
                   [12,13,14,15]])
print(matrix, "\n")
# Q1. matrix를 [3] 행에서 axis 0으로 나누기
'''
[[0  1   2  3]
[4  5   6  7]
[8  9  10 11]],
[12 13 14 15]
'''
a, b = np.split(matrix, [3], axis=0)
print(a, "\n")
print(b, "\n")
# Q2. matrix를 [1] 열에서 axis 1로 나누기
'''
[[ 0]
[ 4]
[ 8]
[12]],
[[ 1  2  3]
[ 5  6  7]
[ 9 10 11]
[13 14 15]]
'''
c, d = np.split(matrix, [1], axis=1)
print(c, "\n")
print(d)
———
 
#집계함수 & 마스킹연산
———
import numpy as np
matrix = np.arange(8).reshape((2, 4))
print(matrix)
# Q1. sum 함수로 matrix의 총 합계를 구해 출력해보세요.
print(np.sum(matrix))
# Q2. max 함수로 matrix 중 최댓값을 구해 출력해보세요.
print(np.max(matrix))
# Q3. min 함수로 matrix 중 최솟값을 구해 출력해보세요.
print(np.min(matrix))
# Q4. mean 함수로 matrix의 평균값을 구해 출력해보세요.
print(np.mean(matrix))
# Q5. sum 함수의 axis 매개변수로 각 열의 합을 구해 출력해보세요.
print(np.sum(matrix, axis=0))
# Q6. sum 함수의 axis 매개변수로 각 행의 합을 구해 출력해보세요.
print(np.sum(matrix, axis=1))
# Q7. std 함수로 matrix의 표준편차를 구해 출력해보세요.
print(np.std(matrix))
# Q8. 마스킹 연산을 이용하여 matrix 중 5보다 작은 수들만 추출하여 출력해보세요.
print(matrix[matrix<5])
——————————————
 
#DataFrame
——————————————
import numpy as np
import pandas as pd
# 두 개의 시리즈 데이터가 있습니다.
print("Population series data:")
population_dict = {
    'korea': 5180,
    'japan': 12718,
    'china': 141500,
    'usa': 32676
}
population = pd.Series(population_dict)
print(population, "\n")
print("GDP series data:")
gdp_dict = {
    'korea': 169320000,
    'japan': 516700000,
    'china': 1409250000,
    'usa': 2041280000,
}
gdp = pd.Series(gdp_dict)
print(gdp, "\n")
# 이곳에서 2개의 시리즈 값이 들어간 데이터프레임을 생성합니다.
print("Country DataFrame")
country = pd.DataFrame({'population' : population, 'gdp' : gdp})
# 데이터 프레임에 gdp per capita 칼럼을 추가하고 출력합니다.
gdp_per_capita = country['gdp']/country['population']
country['gdp per capita'] = gdp_per_capita
# 데이터 프레임을 만들었다면, index와 column도 각각 확인해보세요.
print(country.index)
print(country.columns)
————————————————————————
 
 
# DataFrame값으로 정렬하기
———————————————————————————
import numpy as np
import pandas as pd
print("DataFrame: ")
df = pd.DataFrame({
    'col1' : [2, 1, 9, 8, 7, 4],
    'col2' : ['A', 'A', 'B', np.nan, 'D', 'C'],
    'col3': [0, 1, 9, 4, 2, 3],
})
print(df, "\n")
# 정렬 코드 입력해보기   
# Q1. col1을 기준으로 오름차순으로 정렬하기.
sorted_df1 = df.sort_values('col1')
# Q2. col2를 기준으로 내림차순으로 정렬하기.
sorted_df2 = df.sort_values('col2', ascending=False)
# Q3. col2를 기준으로 오름차순으로, col1를 기준으로 내림차순으로 정렬하기.
sorted_df3 = df.sort_values(['col2', 'col1'], ascending=[True, False])
—————————————————————————————-
 
#조건으로 검색하기  
————-
import numpy as np
import pandas as pd
print("Masking & query")
df = pd.DataFrame(np.random.rand(5, 2), columns=["A", "B"])
print(df, "\n")
#데이터 프레임에서 A컬럼값이 0.5보다 작고 B컬럼 값이 0.3보다 큰값들을 구해봅시다.
print( df[( (df["A"] < 0.5) & (df["B"] > 0.3) )] )
print( df.query("A < 0.5 & B > 0.3"))
————————————————————
 
#그룹으로 묶기
————————————————————
import numpy as np
import pandas as pd
df = pd.DataFrame({
    'key': ['A', 'B', 'C', 'A', 'B', 'C'],
    'data1': [0, 1, 2, 3, 4, 5],
    'data2': [4, 4, 6, 0, 6, 1]
})
print("DataFrame:")
print(df, "\n")
# groupby()로 묶은 데이터에 filter를 적용해봅시다.
# key별 data2의 평균이 3이 넘는 인덱스만 출력해봅시다.
print("filtering : ")
def filter_by_mean(x):
    return x['data2'].mean() > 3;
print(df.groupby('key').filter(filter_by_mean))
# groupby()로 묶은 데이터에 apply도 적용해봅시다.
# 람다식을 이용해 최댓값에서 최솟값을 뺀 값을 적용해봅시다.
print("applying : ")
print(df.groupby('key').apply(lambda x: x.max()-x.min()))
————————————————————————————
 
#역대 월드컵의 관중 수 출력하기
————————————————————————-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
'''
출력 형식을 위한 스켈레톤 코드입니다.
아래 줄 부터 문제에 맞는 코드를 작성해주세요.
'''
world_cups = pd.read_csv("WorldCups.csv")
print(world_cups)
world_cups = world_cups[['Year', 'Attendance']]
print(world_cups)
————————————————————
 
#역대 월드컵의 경기당 득점수
—————————————————————-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
'''
출력 형식을 위한 스켈레톤 코드입니다.
아래 줄 부터 문제에 맞는 코드를 작성해주세요.
'''
world_cups = pd.read_csv("WorldCups.csv")
world_cups = world_cups[['Year', 'GoalsScored', 'MatchesPlayed']]
world_cups['GoalsPerMatch'] = world_cups['GoalsScored']/world_cups['MatchesPlayed']
print(world_cups)
——————————————————————
 
#잭이 심은 가장 두꺼운 콩나무
————————————————-
import pandas as pd
# ./data/tree_data.csv 파일을 읽어서 작업해보세요!
df = pd.read_csv('./data/tree_data.csv')
df = df.sort_values(by=['circumference'], ascending=False)
print(df.iloc[0])
—————————————————
#피리부는사나이를 따라가는 쥐떼

import numpy as np
import pandas as pd
# 파일을 읽어서 코드를 작성해보세요
# 경로: "./data/the_pied_piper_of_hamelin.csv"
df = pd.read_csv('./data/the_pied_piper_of_hamelin.csv')
rat = df[df["구분"] =='Rat']
df2 = rat.pivot_table(index="일차", columns="성별", values="나이", aggfunc=np.mean)
print(df2)
#구분 = 'Children'
————————————————————————————————————————
 
3_파이썬 실전 데이터 분석
 
#새로운 단어 추가하기
———————————————————————————
# 트럼프 대통령 트윗을 공백 기준으로 분리한 리스트입니다. 수정하지 마세요.
trump_tweets = ['america', 'is', 'back', 'and', 'we', 'are', 'coming', 'back', 'bigger', 'and', 'better', 'and', 'stronger', 'than', 'ever', 'before']
def make_new_list(text):
    # 아래 코드를 작성하세요.
    new_list = []
    for i in text :
        if i.startswith('b') :
            new_list.append(i)
   
    return new_list
# 아래 주석을 해제하고 결과를 확인해보세요. 
new_list = make_new_list(trump_tweets)
print(new_list)
—————————————————————————-
 
#특수기호 삭제하기
—————————————————————————
# 트럼프 대통령의 트윗 세개로 구성된 리스트입니다. 수정하지 마세요.
trump_tweets = [
    "i hope everyone is having a great christmas, then tomorrow it’s back to work in order to make america great again.",
    "7 of 10 americans prefer 'merry christmas' over 'happy holidays'.",
    "merry christmas!!!",
]
def remove_special_characters(text):
    processed_text = []
    # 아래 코드를 작성하세요.
   
    for i in text :
        i = i.replace(',', '')
        i = i.replace('!', '')
        i = i.replace('\'','')
        processed_text.append(i)
   
    return processed_text
# 아래 주석을 해제하고 결과를 확인해보세요.
#remove_special_characters(trump_tweets)
print('\n'.join(remove_special_characters(trump_tweets)))
———————————————————————————
 
#데이터형태 변환하기
———————————————————————————
# 텍스트 파일을 불러옵니다.
filename = 'corpus.txt'
def import_as_tuple(filename):
    tuples = []
    with open(filename) as file:
        for line in file:
            # 아래 코드를 작성하세요.
            split = line.split(',')
            word = split[0]
            freq = split[1].replace('\n', '')
           
            new_tuple = (word, freq)
            tuples.append(new_tuple)
        #print(tuples)
           
    return tuples
#import_as_tuple(filename)
# 아래 주석을 해제하고 결과를 확인해보세요. 
print(import_as_tuple(filename))
——————————————————————————
 
#데이터 정렬하기
———————————————————————————
# 단어어 해당 단어의 빈도수를 담은 리스트를 선언합니다. 수정하지 마세요.
pairs = [
    ('time', 8),
    ('the', 15),
    ('turbo', 1),
]
#(단어, 빈도수) 쌍으로 이루어진 튜플을 받아, 빈도수를 리턴합니다.   
def get_freq(pair):
    return pair[1]
#(단어, 빈도수) 꼴 튜플의 리스트를 받아, 빈도수가 낮은 순서대로 정렬하여 리턴합니다.
def sort_by_frequency(pairs):
    return sorted(pairs, key=get_freq)
# 아래 주석을 해제하고 결과를 확인해보세요. 
print(sort_by_frequency(pairs))
———————————————————————————
 
#데이터 빠르게 탐색하기
———————————————————————
# 텍스트 파일을 불러옵니다.
source_file = "netflix.txt"
def make_dictionary(filename):
    user_to_titles = {}
    with open(filename) as file:
        for line in file:
            # 아래 코드를 작성하세요.
           user, title = line.split(":")
            title = title.replace("\n", "")
            user_to_titles[user] = title
        return user_to_titles
# 아래 주석을 해제하고 결과를 확인해보세요. 
print(make_dictionary(source_file))
—————————————————————————-
#JSON 데이터 읽고 생성하기

# json 패키지를 임포트합니다.
import json
#JSON 파일을 읽고 문자열을 딕셔너리로 변환합니다.
def create_dict(filename):
    with open(filename) as file:
        json_string = file.read()
        str = json.loads(json_string)
        # 함수를 완성하세요.
        return str
#JSON 파일을 읽고 딕셔너리를 JSON 형태의 문자a열로 변환합니다.
def create_json(dictionary, filename):
    with open(filename, 'w') as file:
        # 함수를 완성하세요.
        str = json.dumps(dictionary)
        file.write(str)
       
        return str
       
       
       
# 아래 주석을 해제하고 결과를 확인해보세요. 
src = 'netflix.json'
dst = 'new_netflix.json'
netflix_dict = create_dict(src)
print('원래 데이터: ' + str(netflix_dict))
netflix_dict['Dark Knight'] = 39217
create_json(netflix_dict, dst)
updated_dict = create_dict(dst)
print('수정된 데이터: ' + str(updated_dict))

 
#한줄 함수 작성하기

'''
num을 제곱한 값을 리턴합니다.
'''
def _square(num):
    return num * num
# _square()와 동일한 기능을 하는 lambda 함수 square를 만들어 보세요.
square = lambda num: num * num
'''
string이 빈 문자열일 경우 빈 문자열을, 아니면 첫 번째 글자를 리턴합니다.
'''
def _first_letter(string):
    return string[0] if string else ''
first_letter = lambda string: string[0] if string else ''
# assert를 이용하여 두 함수의 기능이 동일한 지 테스트합니다. 아래 주석을 해제하고 결과 값을 확인해보세요.
testcases1 = [3, 10, 7, 1, -5]
for num in testcases1:
        assert(_square(num) == square(num))
testcases2 = ['', 'hello', 'elice', 'abracadabra', '  abcd  ']
for string in testcases2:
    assert(_first_letter(string) == first_letter(string))
# # 위의 assert 테스트를 모두 통과해야만 아래의 print문이 실행됩니다.
print("성공했습니다!")

 
# 리스트에 함수 적용하기

# CSV 모듈을 임포트합니다.
import csv
def get_titles(books_csv):
    with open(books_csv) as books:
        reader = csv.reader(books, delimiter=',')
        # 함수를 완성하세요.
      get_title = lambda row: row[0]
        titles = map(get_title, reader)
       
         
        return list(titles)
# 작성한 코드를 테스트합니다. 주석을 해제하고 실행하세요.
books = 'books.csv'
titles = get_titles(books)
for title in titles:
    print(title)

#트럼프 대통령 트윗 분류하기

def trump_tweet(text) :
    # 주어진 규칙에 맞추어 trump_twit()함수를 구현해주세요.
    # pass는 지우고 코드를 작성해주세요.
    Hashtag = []
    Mention = []
    Message = []
    li = text.split(' ')
    for l in li :
        if(l.startswith('#')):
            Hashtag.append(l.replace('#',''))
        elif(l.startswith('@')):
            Mention.append(l.replace('@', ''))
        else:
            Message.append(l)
   
    print("hash list : ", Hashtag)
    print("mention list : ", Mention)
    print("text list : ", Message)
# 아래 부분은 수정하지 마세요!
# 입력과 출력을 수행하는 코드입니다.
t = input()
trump_tweet(t)

 
#영어 단어 빈도수 찾기

 
def get_freq(pairs) :
    return pairs[1]
def filter_by_text(text) :
    # 주어진 규칙에 맞추어 filter_by_text()함수를 구현해주세요.
    # corpus.txt에 있는 텍스트를 읽어와서 corpus라는 리스트에 추가한다.
    corpus = []
   
    with open('corpus.txt') as file :
        for line in file :
            split = line.split('/')
            t = split[0]
            f = int(split[1].replace('/n', ''))
            new_tuple = (t, f)
            corpus.append(new_tuple)
   
# corpus에 있는 데이터 중, text로 시작하는 단어만을 추려서 result라는 리스트에 저장한다.
    result = []
  for c in corpus :
        if c[0].startswith(text) :
            result.append(c)
   
    result.sort(key = get_freq, reverse=True)
   
    # 찾은 영어 단어를 빈도수를 기준으로 내림차순으로 정렬하여 20개만 출력한다.
    print(result[:20])
   
   
# 아래 부분은 수정하지 마세요!
# 입력과 출력을 수행하는 코드입니다.
t = input()
filter_by_text(t)