DIY-공기청정기

저렴하게 만들수 있다는 장점이 있지만 뭔가 허접. 저처럼 3D프린트기가 없다면.

 

장비 : 자동차 에어컨필터(6천원~15천원), 테이프(1천원), 쿨러팬(죽어버린데스크탑의 팬 재사용), 샤오미보조베터리, 아두이노

 

여기서 아두이노를 사용하는건 계속적으로 전력을 공급하기 위해서 그냥 사용할뿐.

이것 사용안하면 10초후에 보조베터리에서 전력이 끊어짐.

추가로 미세먼지 센서나 led로 측정값에 대한 이벤트를 주는것도 가능하겠음

미세먼지 센서로 측정하게되면 업데이트하는걸로.


데스크탑에서 뺀 쿨러 4pin이다.

노란색선(+), 그 옆 검정색선(-)



그럭저럭^^ 그런데 바람이 좀 많이 약하다.  DIY는 자기 만족이니까. 난 만족한다.

이것 선풍기로 만드는것도 좋겠는데^^.


자바스크립트로 fb API연동하여 로그인하기



그래프 API 탐색기 이용하기

url : https://developers.facebook.com/tools-and-support 



appid 에서 가져올 권한 선택추가 선택


default : id, name 

추가로 가져올 정보 : email






위 api 탐색기로 선 테스트 후 

아래처럼 javascript로 코드작성.

참고url : https://developers.facebook.com/docs/facebook-login/web#logindialog



<<html code>>


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--
reference to : https://developers.facebook.com/tools-and-support
-->
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '2028791704043595',
     cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v3.0' // use graph api version 2.8
});
    FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

   /*
     콜백에 제공되는 response 개체에는 다음과 같은 여러 필드가 포함되어 있습니다.
    {
        status: 'connected',
        authResponse: {
            accessToken: '...',
            expiresIn:'...',
            signedRequest:'...',
            userID:'...'
        }
    }코드 복사
    status는 앱 사용자의 로그인 상태를 지정합니다. 상태는 다음 중 하나일 수 있습니다.
    connected - 사용자가 Facebook에 로그인하고 앱에 로그인했습니다.
    not_authorized - 사용자가 Facebook에는 로그인했지만 앱에는 로그인하지 않았습니다.
    unknown - 사용자가 Facebook에 로그인하지 않았으므로 사용자가 앱에 로그인했거나 FB.logout()이 호출되었는지 알 수 없어,
Facebook에 연결할 수 없습니다.
    connected 상태인 경우 authResponse가 포함되며 다음과 같이 구성되어 있습니다.
    accessToken - 앱 사용자의 액세스 토큰이 포함되어 있습니다.
    expiresIn - 토큰이 만료되어 갱신해야 하는 UNIX 시간을 표시합니다.
    signedRequest - 앱 사용자에 대한 정보를 포함하는 서명된 매개변수입니다.
    userID - 앱 사용자의 ID입니다.
    앱에서 앱 사용자의 로그인 상태를 알게 되면 다음 중 하나를 수행할 수 있습니다.
    사용자가 Facebook과 앱에 로그인한 경우 앱의 로그인된 환경으로 리디렉션됩니다.
    사용자가 앱에 로그인하지 않았거나 Facebook에 로그인하지 않은 경우 FB.login()을 사용하여 로그인 대화 상자에 메시지를
표시하거나 로그인 버튼을 표시합니다.
        */
   function statusChangeCallback(response) {
    
      console.log('statusChangeCallback');

      if (response.status === 'connected') {
        console.log(response.authResponse.accessToken);
        // Logged into your app and Facebook.
        testAPI();
      } else if (response.status === 'not_authorized') {
        document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
      } else {
        document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';
      }

  }

function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
  
function testAPI() {
  console.log('Welcome! Fetching your information.... ');
  FB.api(
    '/me',
    {"fields":"id,name,email"},
    function(response) {
       // Insert your code here
      console.log('Successful login for: ' + response.name);

      document.getElementById('status').innerHTML = JSON.stringify(response);
    }
  );
}

function fblogout(){

  FB.logout(function(response) {
    window.location.reload();
  });
}

</script>

<fb:login-button
scope="public_profile,email"
onlogin="checkLoginState();">
</fb:login-button>

<input type="button" onclick="javascript:fblogout();" value ="로그아웃" />
<div id="status"/>

</body>
</html>


로그인페이지>>


로그인후 fb의 개인정보 받아 display



로그인은 잘 되나, 로그아웃은 아래와 같은 에러내용으로 console log를 찍고 로그아웃이 안되고 있음. 

유투브 동영상등 찾아보고 진행했지만 해결못함.


Refused to display 'https://www.facebook.com/home.php' in a frame because it set 'X-Frame-Options' to 'deny'.


'프로그래밍 > PHP' 카테고리의 다른 글

curl kakao open api사용하기  (0) 2018.08.05
php CURL 사용하기  (0) 2018.07.31
php 패스워드 암호화 bcript  (0) 2018.05.02
unlink(=delete) 메소드 이용하기  (0) 2018.04.22
directory entry 읽어 파일리스트업  (0) 2018.04.20

스크린스크래핑

WebBrowser이용해서 website에 렌더링된 html의 특정값을 추출한다.

예를 들어 특정 사이트 모 카테고리에 있는 내용을 모두 가져와서 데이터화하고 그것을 분석하고 싶을 때 스크래핑을 사용하면 편리하다.

 

아래 code

 

특정 카테고리의의 글list를 통해 key, title을 추출하고

Key를 이용해 본문내용의 text를 가져와서 db화 한 내용이다.

글의 pattern등 분석자료로 사용할 목적으로 데이터가 필요하나 해당사이트에서 DB를공개하진 않으니 이렇게 스크랩핑해서 자료화해서 사용하는 것이다.

이렇게 하지 않으면 사이트의 모든 사이트 내용을 클릭~클릭~클릭~ 하겠지.

 

이렇게 프로그램하기 전에 사전에 해당 사이트를 분석하고 맞게 프로그래밍하면 된다.


step1) 카테고리의의 글list를 통해 key, title을 추출 : webSiteContentsList();

 => 추출된 data를 수작업으로 insert스크립트만들어 TMP_HELP 에 insert함.

step2) Key를 이용해 본문내용의 text를 가져와서 db화 한 내용 : webSiteContentsDetail(oBrowser);


<c# code>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient;

namespace ScrappingWinForms
{
public partial class Form1 : Form
{

int iq = 0;
string contentsKey = "";

string sConnectionString = "Server=localhost;contentsKey=root;Pwd=???;Database=??????";
string sContentsUrl = "http://www.doitforyou.co.kr/sread.html?key="; //fake url임
string sListUrl = "http://www.doitforyou.co.kr/sub.html?&sec=cc&section=culture&page="; //fake url임

String Url = string.Empty;

public Form1()
{
InitializeComponent();

//WebBrowser로 사이트 로딩시 자바스크립트 바인딩안되어 에러나는 경우.
//자바스크립트 오류(dialogbox) 무시하고 진행가능하도록 제어함.
this.webBrowserViewer.ScriptErrorsSuppressed = true;
webBrowserViewer.DocumentTitleChanged += new EventHandler(webBrowserViewer_DocumentTitleChanged);
}
private void btnSearch_Click(object sender, EventArgs e)
{
// surftheWeb();
if (iq < 200)
{
selectContentsKeyfromWebsite();
}
}

#region surftheWeb :WebBrowser에 SitePage 브라우징한다.
private void surftheWeb()
{
Url = txtUrl.Text;
webBrowserViewer.Navigate(Url);
}

private void surftheWeb(String sUrl)
{
webBrowserViewer.Navigate(sUrl);
}

#endregion


#region Select / Update from the WebSite

private void selectContentsKeyfromWebsite()
{
MySqlConnection oConnection = new MySqlConnection(sConnectionString);
oConnection.Open();

try
{
MySqlCommand cmd = oConnection.CreateCommand();
cmd.CommandText = "SELECT HELP_TOPIC_ID FROM TMP_HELP WHERE HELP_TOPIC_ID >= 100 AND DESCRIPTION = '' LIMIT 1";
MySqlDataAdapter aDap = new MySqlDataAdapter(cmd);
DataSet dsData = new DataSet();
aDap.Fill(dsData);
if (contentsKey != dsData.Tables[0].Rows[0][0].ToString())
{
contentsKey = dsData.Tables[0].Rows[0][0].ToString();
String sUrl = String.Empty;
sUrl = sContentsUrl + contentsKey;
surftheWeb(sUrl);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oConnection.State == ConnectionState.Open)
{
oConnection.Close();
}
}
}
/// <summary>
/// key값으로 contents내용을 업데이트 한다.
/// </summary>
/// <param name="sHelp_topic_id"></param>
/// <param name="sDescription"></param>
private void updateContentonIldaro(String sHelp_topic_id, String sDescription)
{
MySqlConnection oConnection = new MySqlConnection(sConnectionString);
oConnection.Open();

try
{
MySqlCommand cmd = oConnection.CreateCommand();
cmd.CommandText = "UPDATE tmp_help set description = @description where help_topic_id = @help_topic_id";
cmd.Parameters.AddWithValue("@help_topic_id", int.Parse(sHelp_topic_id));
cmd.Parameters.AddWithValue("@description", sDescription);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oConnection.State == ConnectionState.Open)
{
oConnection.Close();

//key를 다시 조회한다.
btnSearch_Click(null, null);
}
}
}
#endregion

/// <summary>
/// WebBrowser's DocumentCompleted Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webBrowserViewer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser oBrowser = sender as WebBrowser;
//txtSource.Text = StreamConvertEUCKRtoUTF8(oBrowser);

this.txtUrl.Text = oBrowser.Url.AbsoluteUri;

//webSiteContentsList();
webSiteContentsDetail(oBrowser);
}

private void webSiteContentsDetail(WebBrowser oBrowser)
{
iq++; //반복수행위한 카운팅
getWebSiteContentsDetail(oBrowser);
}

/// <summary>
/// 게시판 글list, Paging있음
/// </summary>
private void webSiteContentsList() {

iq++; //paging 숫자

getData();

if (iq < 21)
{
String sUrl = sListUrl + iq.ToString();
surftheWeb(sUrl);
}
}

/// <summary>
/// 1.WebBrowser로 rendering된 html을 TagName으로 HtmlElementCollection에 담는다.
/// 2.HtmlElementCollection => HtmlElement에 담긴 InnerHtml분석한다.
/// 3.HtmlElement[]에 추출하려는 대상을 담는다.
/// </summary>
/// <param name="wb"></param>
/// <param name="tagName"></param>
/// <returns></returns>
private HtmlElement[] GetElementsByTagName(WebBrowser wb, string tagName)
{
var l = new List<HtmlElement>();

var els = wb.Document.GetElementsByTagName(tagName); // all elems with tag
foreach (HtmlElement el in els)
{
if (el.InnerHtml == null)
{
continue;
}

if(el.InnerHtml.StartsWith("<A href=\"read.html"))
{
l.Add(el);
}
}

return l.ToArray();
}


/// <summary>
/// 1.WebBrowser로 rendering된 html을 TagName으로 HtmlElementCollection에 담는다.
/// 2.HtmlElementCollection => HtmlElement에 담긴 요소들중 className을 이용해서 추출하려는 대상을 뽑는다..
/// 3.HtmlElement[]에 추출하려는 대상을 담는다.
/// </summary>
/// <param name="wb"></param>
/// <param name="tagName"></param>
/// <param name="className"></param>
/// <returns></returns>
private HtmlElement[] GetElementsByTagNClassName(WebBrowser wb, string tagName, string className)
{
var l = new List<HtmlElement>();

var els = wb.Document.GetElementsByTagName(tagName); // all elems with tag
foreach (HtmlElement el in els)
{

if (el.GetAttribute("className") == className)
{
l.Add(el);
}
}

return l.ToArray();
}

/// <summary>
/// 글 상세 페이지에서 추출하고자 하는 Text만 가져온다.
/// </summary>
/// <param name="oBrowser"></param>
private void getWebSiteContentsDetail(WebBrowser oBrowser)
{
var arrCollection = GetElementsByTagNClassName(webBrowserViewer, "td", "contentsbody");
for (int i = 0; i < arrCollection.Length; i++)
{
//Console.WriteLine(arrCollection[i].InnerHtml);

String sText = String.Empty;
//sText = arrCollection[i].InnerHtml;
sText = arrCollection[i].OuterText;

if (sText == null)
{
//글 text가 없는 경우가 있음
//case1) 이미지로 대체한 경우 img html tag가 글 대신 있음
sText = arrCollection[i].InnerHtml;
}
if (contentsKey.Equals(oBrowser.Url.AbsoluteUri.Replace(sContentsUrl, "")))
{
updateContentonIldaro(contentsKey, sText);
}
}
}

private void getData() {

// getting day and night temperature
var arrCollection = GetElementsByTagName(webBrowserViewer, "dt");

DataTable dt = new DataTable();

dt.Columns.Add("contentsKey", typeof(int));
dt.Columns.Add("Title", typeof(string));

Console.WriteLine("-- " + iq.ToString() + " --------------");
txtSource.Text = txtSource.Text + "-- " + iq.ToString() + " --------------" + "\r\n";

for (int i = 0; i < arrCollection.Length; i++) {
//Console.WriteLine(arrCollection[i].InnerHtml);

String sText = String.Empty;
sText = arrCollection[i].InnerHtml;
sText = sText.Replace("<A href=\"sread.html?key=", "").Replace("</A>", "").Replace("\"", "");

String[] arrSplit = sText.Split('>');

dt.Rows.Add(arrSplit[0],arrSplit[1]);

Console.WriteLine(arrSplit[0] + ":" + arrSplit[1]);

txtSource.Text = txtSource.Text + arrSplit[0] + ":" + arrSplit[1] + "\r\n";

}

}

#endregion


reference to :  https://www.codeproject.com/Tips/858775/Csharp-Website-HTML-Content-Parsing-or-How-To-Get


'프로그래밍 > c#' 카테고리의 다른 글

c#에서 mariadb사용하기  (0) 2018.11.10
WebBrowser.DocumentText 한글깨짐  (0) 2018.05.07
using MySqlConnector  (0) 2018.05.07

+ Recent posts