Giter Site home page Giter Site logo

bluehouse_petitions's Introduction

bluehouse_petitions

문재인 전 대통령 청와대 국민청원 데이터 청와대 기록실을 통한 덤프

python lxml 기반으로 작성하였으며, 병렬 크롤링을 위해 ray를 활용하여 데이터를 수집하였습니다.

본인의 컴퓨터 스펙에 맞게 파라미터를 수정해주세요.

worker = 16
size = 3000

Huggingface

Huggingface에서 사용할 수 있도록 데이터를 업로드하였습니다~

bluehouse-national-petition

Requirements

pip install ray requests

Data Shape

number 제목 답변상태 참여인원 카테고리 청원시작 청원마감 청원내용 답변원고

[451513 rows x 9 columns]

RAY Process

import pandas as pd
import requests
from lxml.html import fromstring
from tqdm import tqdm
import gc
import ray
ray.init()


@ray.remote
def main(data, h, ram, iteration):
    if ram == 0 & h > iteration: # 처음위치
        s = h
        e = s-iteration
    elif 0 <= h-iteration*ram <= iteration: # 마지막 위치
        s = h-iteration*ram
        e = -1
    elif h-iteration*ram < 0: # 이전에 마지막 위치를 도달 했으면 빈 df 리턴
        return data.append(pd.Series([None for _ in range(len(columns))]), ignore_index=True)
    else:
        s = h-iteration*ram
        e = s-iteration
    for code in tqdm(range(s, e, -1)):
        try:
            url = "http://webarchives.pa.go.kr/19th/www.president.go.kr/petitions/{}".format(code)
            res = requests.get(url)
            parser = fromstring(res.text)

            title = parser.xpath("/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/h3/text()")
            status = parser.xpath(
                "/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/div[1]/h4/text()")
            personnel = parser.xpath(
                "/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/h2/span/text()")
            category = parser.xpath(
                "/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/div[2]/ul/li[1]/text()")
            start = parser.xpath(
                "/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/div[2]/ul/li[2]/text()")
            end = parser.xpath(
                "/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/div[2]/ul/li[3]/text()")
            q = parser.xpath("/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/div[4]/div[2]/text()")
            a = parser.xpath("/html/body/div[3]/div[2]/section[2]/div[2]/div[1]/div[2]/div[1]/div/div[5]/div/text()")
            data = data.append(pd.Series([code, *title, ' '.join(status), *personnel, *category, *start, *end,
                                          ' '.join(q),
                                          ' '.join(a)]), ignore_index=True)
        except:
            if len(data) > 2:
                return data
            else:
                return data.append(pd.Series([None for _ in range(len(columns))]), ignore_index=True)
    return data


worker = 16
size = 3000
total = round(605368/(size*worker))
columns = ['number', '제목', '답변상태', '참여인원', '카테고리', '청원시작', '청원마감', '청원내용', '답변원고']
for i in range(total):
    df = pd.DataFrame()
    df = ray.put(df)
    starting = 605368 - (size*worker*i)
    ans = [main.remote(data=df, h=starting, ram=n, iteration=size) for n in range(worker)]
    ans = ray.get(ans)
    ans = pd.concat(ans, ignore_index=True)

    ans.columns = columns
    ans = ans.dropna(subset=['청원시작']).reset_index(drop=True)

    ans.to_parquet(f'Bluehouse{i}.parquet', engine='pyarrow', compression='gzip', index=False)
    print(f"{i}th FIN")
    del df
    del ans
    gc.collect()
ray.shutdown()

Preprocess

import pandas as pd

df = pd.read_parquet('Bluehouse.parquet')
df.청원내용 = df.청원내용.str.replace('\t', '', regex=True)
df.청원내용 = df.청원내용.str.replace('\r', '', regex=True)
df.청원내용 = df.청원내용.str.replace('\n', ' ', regex=True)
df.청원내용 = df.청원내용.str.replace('\s+', ' ', regex=True)
df.청원내용 = df.청원내용.str.strip()

df.답변원고 = df.답변원고.str.replace('\t', '', regex=True)
df.답변원고 = df.답변원고.str.replace('\r', ' ', regex=True)
df.답변원고 = df.답변원고.str.replace('\n', '', regex=True)
df.답변원고 = df.답변원고.str.replace('\s+', ' ', regex=True)
df.답변원고 = df.답변원고.str.strip()

df.number = df.number.astype(int)

df.to_parquet('Bluehouse_dump.parquet')

reference

대통령기록관

RAY

bluehouse_petitions's People

Contributors

halokim avatar

Stargazers

 avatar

Watchers

 avatar

bluehouse_petitions's Issues

수집 데이터 문의 드립니다.

안녕하세요 선생님,
카이스트 소셜 컴퓨팅 연구실에서 연구하고 있는 석사과정 학생 김재홍이라고 합니다. 멋진, 수집 코드 올려주심에 정말 감사드립니다.
저는 new media and society 라는 SCI 저널에, Moral Emotion과 사람들의 정치 선택과 관련한 논문을 투고 준비중에 있습니다.

이전에 스스로 짠 코드로 21년 10월까지 데이터를 수집했었는데, 현재 청원사이트가 없어져서 글을 남기게 됐습니다.
청원이 마감된 시점에서, 전수 데이터를 사용할 수 있다면 분석과 결과에 신뢰성을 더할 수 있을 것이라 생각합니다.
혹시, 선생님께서 수집한 데이터를 보관중이시라면 데이터를 요청드려도 괜찮을까요?!
논무을 출간하게 된다면, 마땅히 그리고 당연히 선생님의 github 링크를 인용하도록 하겠습니다.

이렇게 갑자기 글을 남기게 되어 죄송하고, 또한 멋진 코드 만들어주심에 감사드립니다.
김재홍 드림
(mail: [email protected], twitter: @JaehongLuke418)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.