2019. 9. 29.

[python] 위키피디아 데이터 수집 후 DB에 저장

위키피디아 데이터 수집 후 DB에 저장하는 파이썬 코드

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import datetime
import random
import pymysql

conn = pymysql.connect(host='127.0.0.1',user='root',passwd='2kdskfk1!@', db='scraping', charset='utf8')

cur = conn.cursor()
cur.execute("USE scraping")
random.seed(datetime.datetime.now())

def store(title, content):
cur.execute(
"INSERT INTO pages (title, content) VALUES (\"%s\", \"%s\")", (title, content)
)
cur.connection.commit()

def getLinks(articleUrl):
html = urlopen("http://en.wikipedia.org"+articleUrl)
bsObj = BeautifulSoup(html, "html.parser")
title = bsObj.find("h1").get_text()
content = bsObj.find("div", {"id":"mw-content-text"}).find("p").get_text()
store(title, content)
return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$"))

links = getLinks('/wiki/Kevin_Bacon')
try :
while len(links) > 0:
newArticle = links[random.randint(0, len(links)-1)].attrs["href"]
print(newArticle)
links = getLinks(newArticle)
finally:
cur.close()
conn.close()

기본적인 테스트기 때문에 불필요한 값들이 많이 들어가있는 것을 볼 수 있다.


Continue reading

[python] mysql 과 파이썬 연동

파이썬에서 mysql 을 사용하려면 pymysql 모듈을 pip로 설치해야 한다.

import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='비밀번호', db='scraping')

cur = conn.cursor()
cur.execute("SELECT * FROM pages WHERE id=1")
print(cur.fetchall())
cur.close()
conn.close()


Continue reading

2019. 9. 28.

MYSQL 개발 툴로 접속이 안될때

mysql 을 설치하고 나서, cmd command 에서는 접속이 잘되는데,  개발 툴 ( 나의 경우엔 toad for mysql ) 로는 접속이 안된다. 

해결 방안은 다음과 같다. 

1. mysql installer - community 를 설치
2. mysql server 에서 Reconfigure 클릭
3. use Legacy Authentication Method 선택
 

Continue reading

Popular Posts

Recent Posts

Powered by Blogger.