안경잡이개발자

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request
from bs4 import BeautifulSoup


def main():
    url = "https://news.nate.com/recent?mid=n0100"
    sourcecode = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(sourcecode, "html.parser")

    divs = soup.find_all("div", class_="mduSubjectList")
    for div in divs :
        link = div.find("a")["href"]
        print("http:" + link)


if __name__ == "__main__":
    main()



728x90
반응형

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request
from bs4 import BeautifulSoup


def main():

    sourcecode = urllib.request.urlopen("https://news.sbs.co.kr/news/newsflash.do?plink=GNB&cooper=SBSNEWS").read()
    soup = BeautifulSoup(sourcecode, "html.parser")

    list_href = []
    list_content = []

    for href in soup.find_all("div", class_="mfn_inner"):
        list_href.append("https://news.sbs.co.kr" + href.find("a")["href"])

    for i in range(0, len(list_href)):
        url = list_href[i]
        sourcecode = urllib.request.urlopen(url).read()
        soup = BeautifulSoup(sourcecode, "html.parser")
        list_content.append(soup.find("div", class_="text_area").get_text())

    print(list_href)
    print(list_content)


if __name__ == "__main__":
    main()






728x90
반응형

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request
from bs4 import BeautifulSoup


def main():

    for i in range(0, 10):

        url = "http://sports.donga.com/Enter?p=" + str((i * 20) + 1) + "&c=02"
        soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser")

        spans = soup.find_all("span", class_="tit")
        for j in range(0, 20):
            print((i * 20) + j + 1, "번째 글:", spans[j + 3].get_text())

if __name__ == "__main__":
    main()


  또한 혹은 특정한 뉴스 기사 목록 페이지에서, 각 뉴스 기사 상세 페이지의 링크를 얻고 싶다면 다음과 같이 할 수 있습니다.


import urllib.request
from bs4 import BeautifulSoup


def main():

    url = "http://sports.donga.com/Enter?p=1&c=02"
    soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser")

    spans = soup.find_all("span", class_="tit")
    for i in range(0, 20):
        print(spans[i + 3].find("a")["href"])

if __name__ == "__main__":
    main()


728x90
반응형

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request
from bs4 import BeautifulSoup


def main():

    url = "https://pann.nate.com/talk/344403021"
    soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser")

    comments = []

    for i in soup.find_all("dd", class_="usertxt"):
        comments.append(i.get_text().strip("\n\t "))

    print(comments)


if __name__ == "__main__":
    main()


728x90
반응형

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request
from bs4 import BeautifulSoup

def main():
    url = "https://movie.naver.com/movie/bi/mi/review.nhn?code=156464"
    soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser")

    ul = soup.find("ul", class_="rvw_list_area")
    for i in ul.find_all("li"):
        print(i.strong.get_text())

if __name__ == "__main__":
    main()



728x90
반응형

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request
from bs4 import BeautifulSoup

def main():
    soup = BeautifulSoup(urllib.request.urlopen("https://www.clien.net/service/group/community").read(), "html.parser")

    list_title = []
    list_nickname = []

    for i in soup.find_all("span", class_="subject_fixed"):
        list_title.append(i.get_text())

    for i in soup.find_all("span", class_="nickname"):
        list_nickname.append(i.get_text())

    print(list_title)
    print(list_nickname)

if __name__ == "__main__":
    main()


728x90
반응형

728x90
반응형

  소스코드는 다음과 같습니다.


import urllib.request from bs4 import BeautifulSoup def main(): url = "http://www.kyeonggi.com/news/articleList.html?sc_section_code=S1N2&view_type=sm" soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser") list_title = [] list_content = []

# 기사 제목 파싱 for news_title in soup.find_all("div", class_="list-titles"): list_title.append(news_title.get_text())

# 기사 요약 파싱 for news_content in soup.find_all("p", class_="list-summary"): list_content.append(news_content.get_text()) print(list_title) print(list_content) if __name__ == "__main__": main()





728x90
반응형

728x90
반응형

  아래 소스코드를 이용하면 네이버 인기 검색어를 파싱할 수 있습니다. 왜냐하면 인기 검색어는 공통적으로 "ah_k"라는 클래스로 묶여 있기 때문입니다.


import urllib.request
from bs4 import BeautifulSoup

def main():
    sourcecode = urllib.request.urlopen("http://www.naver.com").read()
    soup = BeautifulSoup(sourcecode, "html.parser")
    list = []
    for naver_text in soup.find_all("span", class_="ah_k"):
        list.append(naver_text.get_text())
    print(list)

if __name__ == "__main__":
    main()


728x90
반응형

728x90
반응형

  파이썬(Python)의 Matplotlib 라이브러리는 선 그래프 말고도 정말 다양한 형태의 그래프를 지원합니다. 


※ 막대 그래프 ※


  막대 그래프틑 bar() 함수를 이용해서 그릴 수 있습니다.


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-9, 10)
plt.bar(x, x ** 2)
plt.show()


  누적 막대 그래프 형태도 사용할 수 있습니다.


import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(10) # 아래 막대
y = np.random.rand(10) # 중간 막대
z = np.random.rand(10) # 위 막대
data = [x, y, z]
x_array = np.arange(10)
for i in range(0, 3): # 누적 막대의 종류가 3개
    plt.bar(
        x_array, # 0부터 10까지의 X 위치에서
        data[i], # 각 높이(10개)만큼 쌓음
        bottom=np.sum(data[:i], axis=0)
    )
plt.show()


※ 스캐터(Scatter) 그래프 ※


  이제 스캐터(Scatter) 그래프를 먼저 알아보도록 하겠습니다. 그래프를 그릴 때 3번째 인자로 마커의 종류를 입력하면, 알아서 스캐터 그래프로 인식합니다.


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-9, 10)
y1 = x ** 2
y2 = -x
plt.plot(
    x, y1, "*",
    markersize=10,
    markerfacecolor="blue",
    markeredgecolor="red"
)
plt.show()


  혹은 바로 scatter() 함수를 이용해서 스캐터를 그릴 수 있습니다.


import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(10)
y = np.random.rand(10)
colors = np.random.randint(0, 100, 10)
sizes = np.pi * 1000 * np.random.rand(10)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.7)
plt.show()


※ 히스토그램 그래프 ※


  히스토그램 그래프 또한 그릴 수 있습니다. 정규분포 그래프를 나타낼 때에도 많이 사용됩니다.


import matplotlib.pyplot as plt
import numpy as np

data = np.random.randn(10000)
plt.hist(data, bins=1000)
plt.show()


  이 때 bins 속성은 어느 정도 X 간격으로 히스토그램을 출력할 지를 설정하도록 해줍니다. 1000을 넘어서면 다소 그래픽 처리에 시간이 소요될 수 있습니다.

728x90
반응형

728x90
반응형

  파이썬(Python)에서 Matplotlib 라이브러리는 다양한 데이터를 시각화할 수 있도록 도와주는 라이브러리입니다.


  가장 간단한 예제로 (1, 1), (2, 2), (3, 3)을 선으로 잇는 그래프를 만들어보도록 하겠습니다.

import matplotlib.pyplot as plt x = [1, 2, 3] y = [1, 2, 3] plt.plot(x, y) plt.title("My Plot") plt.xlabel("X") plt.ylabel("Y") plt.show()


  그래프를 그림 형태로 저장하기 위해서는 plt.savefig(그림 파일) 명령어를 이용하여 저장할 수 있습니다. 또한 하나의 그림 파일에 여러 개의 그래프가 들어가도록 코딩을 할 수도 있습니다.


import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, np.pi * 10, 500) # PI * 10 넓이에, 500개의 점을 찍기 fig, axes = plt.subplots(2, 1) # 2개의 그래프가 들어가는 Figure 생성 axes[0].plot(x, np.sin(x)) # 첫 번째 그래프는 사인(Sin) 그래프 axes[1].plot(x, np.cos(x)) # 두 번째 그래프는 코사인(Cos) 그래프 fig.savefig("sin&cos.png")


※ 선 그래프 ※


  이제 선 그래프를 그리는 방법에 대해서 알아보도록 하겠습니다. 가장 간단한 예제부터 알아봅시다.


import matplotlib.pyplot as plt import numpy as np x = np.arange(-9, 10) y = x ** 2 plt.plot(x, y, linestyle=":", marker="*") plt.show()


  라인 스타일로는 '-', ':', '-.', '--' 등이 사용될 수 있습니다. 또한 X축 및 Y축에서 특정 범위를 자를 수도 있습니다.


import matplotlib.pyplot as plt import numpy as np x = np.arange(-9, 10) y = x ** 2 plt.plot(x, y, linestyle="-.", marker="*") plt.xlim(-5, 5) plt.show()


  하나의 사진에 두 개의 라인 그래프를 그려 보겠습니다.


import matplotlib.pyplot as plt import numpy as np x = np.arange(-9, 10) y1 = x ** 2 y2 = -x plt.plot(x, y1, linestyle="-.", marker="*", color="red", label="y = x * x") plt.plot(x, y2, linestyle=":", marker="o", color="blue", label="y = -x") plt.xlabel("X") plt.ylabel("Y") plt.legend( shadow=True, borderpad=1 ) plt.show()




728x90
반응형