<jupyter_start><jupyter_text>코스피 시가총액 순위4개 페이지 다운받아 csv 파일로 저장하기<jupyter_code>import csv
import numpy as np
import re
import requests
from bs4 import BeautifulSoup
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"}
url = "https://finance.naver.com/sise/sise_market_sum.nhn?sosok=0&page="
rm 시가총액1-200.csv
filename = "시가총액1-200.csv"

f = open(filename, "w", encoding="utf-8-sig", newline="")
writer = csv.writer(f)
page = "1"
res = requests.get(url + str(page), headers=headers)
#res = requests.get(url + str(page))
res.raise_for_status()
soup = BeautifulSoup(res.text, "lxml")
data_rows = soup.find('table', attrs={"class":"type_2"}).find("tbody").find_all("tr")
for row in data_rows:
    columns = row.find_all("td")
    if len(columns) <= 1:
        continue
    data = [column.get_text().strip() for column in columns]  # 1 줄 반복문으로 "columns 에서 column 를 하나씩 꺼내어 문자열 가져오기"
    print(data)
    #writer.writerow(data)
title = "N	종목명	현재가	전일비	등락률	액면가	시가총액	상장주식수	외국인비율	거래량	PER	ROE".split("\t")
print(type(title)) # title 의 List 형인지 check
writer.writerow(title)
for page in range (1, 5):
    res = requests.get(url + str(page), headers=headers)
    res.raise_for_status()
    soup = BeautifulSoup(res.text, "lxml")
    
    data_rows = soup.find('table', attrs={"class":"type_2"}).find("tbody").find_all("tr")
    
    for row in data_rows:
        columns = row.find_all("td")
        if len(columns) <= 1:
            continue
        data = [column.get_text().strip() for column in columns]  # 1 줄 반복문으로 "columns 에서 column 를 하나씩 꺼내어 문자열 가져오기"
        #print(data)
        writer.writerow(data)
f.close()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15206035983749275, 'fraction_numerical': 0.02901915264074289, 'mean_word_length': 3.9398280802292263, 'pattern_counts': {'":': 3, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '67819', 'license': 'MIT', 'n_tokens_mistral': 763, 'n_tokens_neox': 832, 'n_words': 159, 'path': 'shared/notebooks/2_web-scraping-I/12_csv_stock.ipynb', 'repo_name': 'jungfrau70/docker-sqldb', 'size': '1723'}