2019. 10. 30.

[python] 크롤링 데이터를 mysql에 삽입

이전 포스트(https://coashanee5.blogspot.com/2019/10/blog-post_29.html)는 공공기관의 채용공고 사이트의 검색결과를 수집하여 기업명과, 공고URL을 출력하였다. 이번 포스트에서는 수집한 내용을 데이터베이스에 넣어 보도록 하겠다.

1. 우선 mysql을 설치를 한 후, 데이터를 넣기 위한 데이터베이스를 만든다. 
create DataBase scraping;
2. 이번에는 데이터를 저장할 테이블을 생성한다. 
create Table job_offer (id BIGINT(7) NOT NULL AUTO_INCREMENT, comp VARCHAR(200), title VARCHAR(200), URL VARCHAR(1000), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id));

3. 기존 소스에 DB연결과 데이터를 저장하는 내용을 추가한다.

# 공공기관 채용정보에서 정보통신 공고만 추려서 리스팅하는 소스
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import ssl
import datetime
import pymysql
context = ssl._create_unverified_context()


# url을 변수에 삽입하여 저장한다.
url = "https://job.alio.go.kr/recruit.do?pageNo=1&param=&search_yn=Y" \
      "&idx=&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
      "&work_type=R1030&career=R2020&education=R7010&education=R7040&education=R7050" \
      "&education=R7060&replacement=N&s_date=2019.03.12&e_date=2019.10.12&org_name=&title=&order=REG_DATE"

conn = pymysql.connect(host='127.0.0.1', user='root',passwd='test1234', db='mysql')
cur = conn.cursor()
cur.execute("USE scraping")

html = urlopen(url, context=context)
bsObj = BeautifulSoup(html.read(), "html.parser")

table = bsObj.find("table",class_="tbl type_03")

def extractNumber(word):
    i = int(re.findall('\d+', word)[0])
    return i

def store(comp, title, URL):
    cur.execute(
        "INSERT INTO job_offer (comp, title, URL) VALUES (\"%s\", \"%s\", \"%s\")", (comp, title, URL)
    )
    cur.connection.commit()

list = []
trs = table.tbody.findAll("tr")
for idx, tr in enumerate(trs):
    title = tr.select("td")[2].get_text().strip() # 제목
    comp = tr.select("td")[3].get_text().strip() # 기업명
    a = extractNumber(tr.select("td")[2].find("a").attrs['onclick'])

    new_url = "https://job.alio.go.kr/recruitview.do?pageNo=1&param=&search_yn=Y&idx={0}" \
              "&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
              "&work_type=R1030&career=R2020&education=R7010&education=R7040" \
              "&education=R7050&education=R7060&replacement=N&s_date=2019.03.12" \
              "&e_date=2019.10.12&org_name=&title=&order=REG_DATE".format(a)
    print(idx, title, comp, new_url)
    store(comp, title, new_url)

cur.close()
conn.close()

실행결과, 다음과 같이 데이터가 저장되는 것을 확인할 수 있다.


Continue reading

2019. 10. 29.

[python] 공공기관 채용정보시스템의 채용공고 출력하는 파이썬코드

공공기관 채용정보시스템에서 원하는 공고를 검색하여 크롤링하는 소스이다.

# 공공기관 채용정보에서 정보통신 공고만 추려서 리스팅하는 소스
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import ssl
import datetime
context = ssl._create_unverified_context()


# url을 변수에 삽입하여 저장한다.
url = "https://job.alio.go.kr/recruit.do?pageNo=1&param=&search_yn=Y" \
      "&idx=&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
      "&work_type=R1030&career=R2020&education=R7010&education=R7040&education=R7050" \
      "&education=R7060&replacement=N&s_date=2019.03.12&e_date=2019.10.12&org_name=&title=&order=REG_DATE"

html = urlopen(url, context=context)
bsObj = BeautifulSoup(html.read(), "html.parser")

table = bsObj.find("table",class_="tbl type_03")

def extractNumber(word):
    i = int(re.findall('\d+', word)[0])
    return i

list = []
trs = table.tbody.findAll("tr")
for idx, tr in enumerate(trs):
    title = tr.select("td")[2].get_text().strip() # 제목
    gName = tr.select("td")[3].get_text().strip() # 기업명
    #place = tr.select("td")[4].get_text().strip().replace("\t","").replace("\r","").replace("\n","") # 장소
    #type = tr.select("td")[5].get_text().strip() # 고용 형태
    a = extractNumber(tr.select("td")[2].find("a").attrs['onclick'])

    new_url = "https://job.alio.go.kr/recruitview.do?pageNo=1&param=&search_yn=Y&idx={0}" \
              "&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
              "&work_type=R1030&career=R2020&education=R7010&education=R7040" \
              "&education=R7050&education=R7060&replacement=N&s_date=2019.03.12" \
              "&e_date=2019.10.12&org_name=&title=&order=REG_DATE".format(a)
    #list.append(title + ", " + gName + ", "+new_url)
    print(idx, title, gName, new_url)
#print (list)

실행 결과는 아래와 같다. 



이후에는 크롤링 결과를 1) 엑셀 다운로드, 2) 메일 전송 3) 웹 서버에 띄우기 이런 정도로 포스팅을 해 볼까 생각중이다.

Continue reading

구글 블로거 꾸미기 -5 google blog 에서 소스코드 하이라이트 (highlight)

블로그 성격상 소스코드를 작성할 일이 많은데, 소스코드를 멋지게 작성하는 방법을 소개한다.

1. Highlight.js
코드 구문 강조를 위한 자바스크립트 라이브러리이다. 자동으로 언어를 감지하여 알맞는 표식을 삽입한다.

  • http://highlightjs.org/ 사이트에서 다운로드가 가능하다.

홈페이지에 보면 hosted와 custom package 두 가지 방법이 있다고 나와 있는데, google blog는 hosted 방식을 사용하면 된다. 아래 소스를 html 소스 중 <head></head> 안에 삽입하면 사용할 준비는 끝이다.
<link rel="stylesheet" href="//cdn.jsdelivr.net/highlight.js/8.7/styles/monokai_sublime.min.css" />
<script src="//cdn.jsdelivr.net/highlight.js/8.7/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
이제 포스팅 할때 <pre><code>소스코드 </code></pre> 이렇게 사용하면 된다. 간혹 언어를 인식하지 못하는 경우가 있는데 그럴 경우는 <pre><code="language-html>소스코드 </code></pre> 이런식으로 사용하고자 하는 언어를 입력하면 된다.


import execjs
execjs.eval("'red yellow blue'.split(' ')")

ctx = execjs.compile("""
function add(x, y) {
return x + y;
}
""")

print(ctx.call("add", 1, 2))

파이썬 코드를 예시로 들면 이런 형태의 디자인이 된다. 또한 css 파일의 링크를 바꾸면 원하는 디자인으로 테마를 마음대로 바꿀 수 있다.

** TIPS
가끔 다른 종류의 태그가 삽입되면 하이라이트가 작동 못하는 경우가 있는데, 이 경우 해당 사이트(http://accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php)에서 코드를 넣고 스크립트를 치환하여 시도해보자.

예를들면, <strong>굵게</strong> 를 &lt;strong&gt;굵게&lt;/strong&gt;  이렇게!

Continue reading

Popular Posts

Recent Posts

Powered by Blogger.