RADIO 버튼 체크된 값 가져오기
여러개의 라디오 버튼에서 체크된 값을 가져오기 $('input[name="state"]:checked').val() <input type="radio" name="state" value="0" >끄기 <input type="radio" name="state" value="1" >켜기
키자드에 등록된 총 535개의 포스트를 확인하실 수 있습니다.
여러개의 라디오 버튼에서 체크된 값을 가져오기 $('input[name="state"]:checked').val() <input type="radio" name="state" value="0" >끄기 <input type="radio" name="state" value="1" >켜기
* JQuery 최신버전 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> * JQuery 최신버전 확인 및 다운 링크 : http://docs.jquery.com/Downloading_jQuery
선택 된 radio 버튼의 값 가져오기 $(':radio[name="linkOpt"]:checked').val() <input type="radio" name="linkOpt" value="0" > 현재창 <input type="radio" name="linkOpt" value="1" > 새창 <input type="radio" name="linkOpt" value="2" > 링크없음
* 사이트 : http://sphinxsearch.com . 스핑크스는 풀 텍스트 검색엔진이다. C++로 제작되어 인덱싱 및 검색이 자바로 만든 다른 검색엔진보다 빠르다고한다. 물론, 가장 좋은 점은 공짜라는거... 자세한 사항은 사이트에 들어가서 확인바람 . GROUP BY, LIMIT, ORDER BY 쿼리에 대해 최적화 . RT Indexer 지원 * 인덱싱 : mysql 데이터를 인덱싱해서 스핑크스 데이터로 만드는 작업 . sphinx.conf 에 아래 내용을 설정 1) source 설정 . 인덱스명을 지정하고 어떤 데이터를 인덱싱 할 것인지 설정 . sql_query의 첫번째 값은 중복되지 않는 primary 또는 unique 값이 필요 source zipcode { type = mysql sql_host = localhost sql_user = DB아이디 sql_pass = DB패스워드 sql_db = DB명 sql_port = 3306 # optional, default
* 홈페이지 : http://touchslider.com * 예제소스 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="js/jquery.touchslider.js"></script> <script> $(document).ready( function() { $(".touchslider").touchSlider( { mouseTouch: true } ); }); </script> </head> <body> <div class="touchslider"> <div class="touchslider-viewport" style="width:288px;overflow:hidden;position:relative;height:332px"> <div style="
페이지를 아래로 내리면 TOP 버튼이 나와서 누르면 최상단으로 이동하는 버튼구현 <div class="btn_gotop" style="display:none"> <a href="javascript:void(0);">TOP</a> </div> <script> $(document).ready( function(){ //따라다니는 TOP버튼 $(window).on("scroll touchmove mousewheel DOMMouseScroll", function(e) { if($(window).scrollTop() >= 20) $(".btn_gotop").fadeIn(); else $(".btn_gotop").fadeOut(); }); $(".btn_gotop").click(function(){ $("html,body").animate({ scrollTop: 0 }, "fast"); }); }); </script>
요즘 HTTPS 적용을 많이들 진행하는데 아래 사이트에 들어가면 얼마나 적용을 잘했는지 테스트해준다. 자신이 관리하는 사이트가 있다면 테스트해보자. * https://www.ssllabs.com Qualys SSL Labs HOW WELL DO YOU KNOW SSL? If you want to learn more about the technology that protects the Internet, you’ve come to the right place. Test your server » Test your site’s certificate and configuration Test your browser » Test your browser’s SSL implementation SSL Pulse » See how other web sites are do... www.ssllabs.com
사이트가 어떤 언어로 만들어졌는지 확인하는 프로그램 chrome, firefox 에서 사용가능하니 설치해서 사용하면 편하다 https://www.wappalyzer.com/ Wappalyzer - Identify technologies on websites In the last six months, Wappalyzer identified 1,112 technologies 29,579,606,703 times on 91,284,629 websites Technology lookup Find out what technology a website is built with. Market leaders These are the leading technologies per industry. Category Market Leader www.wappalyzer.com
php의 데이터를 javascript 에 넣을 때 특수문자 (', ", 개행문자) 때문에 오류가 발생한다. 이럴 때 아래와 같이 처리해서 넘겨주면 된다. $temp = str_replace("\r\n","\\r\\n", addslashes($temp));
PHP 로 디비값을 읽어와 JQUERY로 TEXTAREA 넣을 때 처리 (", ', 개행문자를 처리해줘야한다) - PHP 처리 $temp = str_replace("\r\n","\\r\\n", addslashes($temp)); - JQUERY 처리 jQuery('textarea[name="content[]"]').eq($i).val('<?=$temp?>');
LEFT OUTER JOIN 여러개를 붙일 때 형식이다. select a.*,b.*, c.* from TBL1 a left outer join TBL2 b on a.key=b.key left outer join TBL3 c on a.key=c.key and c.sort='0' where a.key='1234'
$con1 = mysql_connect($host, $user, $pass); $con2 = mysql_connect($host, $user, $pass); $con3 = mysql_connect($host, $user, $pass); 위와 같이 여러개의 디비연결 했을 때 의도는 각각의 연결이나 시스템상에서는 하나의 세션으로 처리된다. 그래서 만약 mysql_close($con2) 으로 2번 연결 을 종료시키면 1~3번 모두의 연결이 끊기게 된다. 이렇게 여러개의 연결을 사용할 경우 mysql_connect 함수의 네번째 입력값인 $new_link를 사용해야한다. defualt 값은 false 이고 true 로하면 다중연결이 된다. $con1 = mysql_connect($host, $user, $pass, true); $con2 = mysql_connect($host, $user, $pass, true); $con3 = mysql_connect($host, $user, $pass,
json_encode 사용 시 한글이 깨져서 나오는 경우가 있다 아래와 같이 대응해주면 된다. * PHP 5.4 이상 버전 - JSON_UNESCAPED_UNICODE 옵션사용 . json_encode($str, JSON_UNESCAPED_UNICODE) * PHP 5.4 이하 버전 - 아래 함수 사용 function json_encode2($arr){ array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); }); return mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); }
버튼을 오른쪽 정렬하고 싶은 경우 아래와 같이 처리 1. <input type='button' class='btn' name='btn' value='버튼' style="float: right;"> 2. <div style='width:80px;float: right;'> <input type='button' class='btn' name='btn' value='버튼'> </div>
FIND 명령어로 여러개의 파일 확장자를 찾을 때 아래와 같이 실행 find . \( -name '*.jpg' -o -name '*.mp4' -o -name '*.txt' \)
<input type="text" id="test" name="test" class="test" /> * ID 값 기준으로 가져오기 var value = $('#test'.val()); * NAME 값 기준으로 가져오기 var value = $("input[name=test]").val(); * CLASS 값 기준으로 가져오기 var value = $(".test").val();
입력한 이메일의 유효성을 체크하는 방법 var emailChk = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; if(!emailChk.test($("#oMail").val())) { alert('이메일 주소가 유효하지 않습니다'); return false; }
라라벨과 POST 값 연동 시 토큰 연동을 하지 않는경우 아래와 같은 메세지가 나온다. Error - 419 Sorry, your session has expired 이럴 경우 토큰사용을 off 시켜 사용할 수 있다. 끄는 방법은 아래와 같다. app/Http/Kernel.php 파일에서 protected $middlewareGroups =[ ..... //\App\Http\Middleware\VerifyCsrfToken::class, -> 위 부분 주석처리
url 에서 도메인만 추출하는 방법으로 parse_url 함수를 사용하면된다. $temp = parse_url("https://news.naver.com/main/read.nhn?mode=LSD&mid=shm&sid1=104&oid=001&aid=0011090618"); echo $temp['host'];
<div class="main_box2_dllist3" style="display:none;"> </div> $('.main_box2_dllist3').slideToggle(500); 해당 영역을 슬라드 처럼 열고 닫는다ㄴ
if에서 0과 false 를 구분해야 할 경우가 있다. 보통 php 함수를 사용할 때 리턴 값 이 0일 경우도 있고 false 일 경우도 있는 경우가 있다. 이런 경우 아래와 같이 하면 구분이 되지 않는다. . if($a==false) echo "false"; a값이 0일 경우도 false 로 인식하기 때문이다. 이럴 경우 ===을 사용해야한다. . if($a===false) echo "flase"; 간단한게 설명하면 엄격한 비교라고 생각하면된다.
* 파일명 pathinfo($_FILES['File']['name'], PATHINFO_FILENAME) * 확장자 pathinfo($_FILES['File']['name'], PATHINFO_EXTENSION) echo end(explode('.', $_FILES['file']['name']));
API 를 이용하여 트위터에 글등록하는 방법이다. 먼저, 개발자 사이트에 들어가서 개발자 등록해한다. . https://developer.twitter.com/ 입력할 것도 많고 여러 단계로 이뤄진다. 두번째로 앱을 생성한다. 앱을 생성하면 API KEY가 나오고 ACCESS TOKEN 생성을 클릭하면 토큰이 생성된다. 메모해 두자 https://github.com/jublo/codebird-php 에 들어가서 다운로드 및 설명서를 읽어보자. 아래는 글등록하는 부분만 테스트해본 소스이다. <?php include_once('./src/codebird.php'); //Consumer API keys $cApiKey = ""; $cApiSKey = ""; //Access token $aToken = ""; $aTokenSecret = ""; \Codebird\Codebird::setConsumerKey($cApiKey, $cApiSKey); $cb = \Codebird\Codebird:
FFMPEG 을 이용하여 동영상 2개를 합치는 방법이다. 일단 동영상들은 동일한 인코딩이 되어 있어야한다. txt 파일에 합치기를 원하는 동영상 리스트를 아래와 같이 넣는다 file test1.mp4 file test2.mp4 file test3.mp4 txt 파일을 저장후 아래와 같이 명령어를 처리한다. ffmpeg -f concat -i 'list.txt' -c copy 신규동영상 파일명
요일을 가져오는 함수는 DAYNAME() 이다. 사용하면 Monday, Tuesday, Wednesday 이런 식으로 요일을 리턴한다. 아래는 예제 . SELECT b_date FROM TBSVCS_SCHEDULE WHERE DAYNAME(b_date)='Monday'
select box 값을 변경하지 못하도록 disabled 시킬 경우가 있는데 이럴경우 post 값으로 해당 값이 넘어가지 않는다. 그래서 값을 받고 싶을 경우 따로 값을 넘기거나 아래와 같이 disabled 속성을 제거 하고 submit 시키면 된다 $("select[name=year]").removeAttr('disabled');
탐색기를 실행하면 첫화면에 최근에 사용된... 이란 메뉴가 노출된다. 이를 제거하고 싶을 경우 아래와 같이 하면 된다. 1. 탐색기 실행 2. 상단 메뉴의 보기 클릭 3. 옵션메뉴 클릭 4. 일반탭에서 개인정보보호>빠른 실행에 최근에 사용된 파일, 폴더 표시 체크해제
k380 키보드를 윈도우에서 사용할 경우 한영키가 그냥은 작동하지 않고 fn+한영키를 눌러야 작동하는 경우가 있다. 이럴경우 첨부되어 있는 레지스트리를 실행하여 적용하고 재시작하면 문제가 해결된다. 첨부파일 logi-k380-korean.reg.zip 파일 다운로드
자바스크립트로 입력값의 형식을 체크하는 방법이다. . YYYY-MM-DD HH:II:SS 형식체크 var dateChk = /[0-9]{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) [0-9]{2}:[0-9]{2}:[0-9]{2}/; if ( !dateChk.test("2019-02-02 13:13:13") ) { alert("형식이 맞지 않습니다"); return; }
* 체크여부 확인 . $('input:checkbox[id="boxid"]').is(":checked") . 선택은 true, 미선택은 false 를 리턴한다 * 체크하기 . $("input:checkbox[id='ID']").prop("checked", true); . $("input:checkbox[name='NAME']").prop("checked", false);
web share api 는 네이티브 공유 다이얼로그를 열어주는 방법을 제공한다. 쉽게 말해서 폰에 내장되어 있는 SNS 공유하기 기능을 실행시켜준다는거다. 단점은 지원 브라우저가 제한되어 있다는거다. 자세한 사항은 아래 웹 페이지를 확인하자. 해당 기능을 사용하려면 웹페이지가 https 를 사용해야한다. . https://www.w3.org/TR/web-share/ Web Share API Abstract This specification defines an API for sharing text, links and other content to an arbitrary destination of the user's choice. The available share targets are not specified here; they are provided by the user agent. They could, for example, be apps, websites or contac...
오늘을 기준으로 이벤트 날짜까지 몇일 남았는지 계산 $today = date("Y-m-d"); $eventDay = "2020-04-15"; $d_day = intval( (strtotime($eventDay) - strtotime($today) ) / 86400 );
등록된 글을 sns 처럼 시간표시할때 아래의 함수를 사용하면 몇분전, 몇시간전, 몇일전으로 표시할 수 있다 $date = strtotime("2020-03-12 17:00:00") echo showTime($date); function showTime($date){ $time = time()-$date; $list = array('31536000'=>'년', '2592000'=>'개월', '604800'=>'주', '86400'=>'일', '3600'=>'시간', '60'=>'분', '1'=>'초'); foreach ($list as $k=>$v){ if (0 !=$c=floor($time/(int)$k)) { return $c.$v.'전'; } } }
$str 에서 숫자만 리턴한다 $str = "5분전"; preg_replace("/[^0-9]*/s","",$str);
사이트 : https://simplehtmldom.sourceforge.io/ 설치없이 간단하게 사용할 수 있는 php 용 크롤링 api include_once '../simplehtmldom/HtmlWeb.php'; use simplehtmldom\HtmlWeb; // Download a page $doc = new HtmlWeb(); $html = $doc->load('https://www.naver.com'); //li 태그 클래스명으로 찾기 $rst=$html->find('li[class=ofra_list_item]') //첫번째 a 태그 찾기 $rst=$html->find('a', 0) //div 태그 클래스명으로 찾기 $rst=$html->find('div[class=ofra_list_tx_headline]', 0) //텍스트 가져오기 $rst->plaintext //href 값 가져오기 $rst->href
사이트 : https://github.com/FriendsOfPHP/Goutte 깊게 사용해보지 않았으나 조사결과 강력한 크롤링 도구라고 한다. 설치가 필요하다. require __DIR__. "/vendor/autoload.php"; use Goutte\Client; use Symfony\Component\HttpClient\HttpClient; $client = new Client(HttpClient::create(['timeout' => 60])); $crawler = $client->request('GET', 'https://media.naver.com/press/052'); //ofra_list_item 클래스를 사용하는 li 태그안의 모든 텍스트 가져오기 $crawler->filter("li.ofra_list_item")->each(function ($node) { echo $node->text(); }); //a 태그의 href 가져오기 $node->filter("a")
원하는 날짜형식으로 변경하고 싶으면 date_create 와 date_format 을 사용하면 된다. $date = "2020-07-09 17:34:27"; echo date_format(date_create($date), "Y년 m월 d일"); //오전, 오후 str_replace(array("AM","PM"), array("오전","오후"), date_format(date_create($date), "Y년 m월 d일 A h시 i분"))
아래와 같이 HTML 구조가 있을 경우 <div id='TEST'> <ul> <li>1</li> </ul> <ul> <li>2</li> </ul> </div> TEST DIV 에 UL 을 추가 var plus = document.createElement('ul'); plus.innerHTML = "<li>3</li>"; document.getElementById('TEST').appendChild(plus);
PHP 배열 -> 자바스크립트 배열 <? $temp = array( array(1, 2, 3, 'a'), array(4, 5, 6, 'b') ); ?> <script> var jarray = <?=json_encode($temp)?>; </script>
내용 추가할 때 애니메이션 효과 넣고 화면 스크롤되지 않게 하기 var temp = <?=json_encode("<span>".nl2br($mContent)."</span>")?>; var top; top = $(window).scrollTop(); $(temp).hide().appendTo("#content").fadeIn("slow"); $(window).scrollTop(top);
파비콘이란 즐겨찾기 아이콘이며 브라우저 탭의 제목 앞에 나오는 아이이콘 이미지이다. 등록방법은 아래와 같이 태그를 넣어주면된다. (타이틀 태그밑에...) <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon">
URL로 파일정보 가져오기 원격에 있는 파일의 정보를 가져오는 방법은 아래와 같이 다운로드 형식으로 처리할 수 밖에 없는 것 같다. 대용량 파일의 경우 아무래도 오래걸릴 수 밖에 없다. include "getid3.php"; $getID3 = new getID3; $url = "http://test.com/test.mp4"; $filename = tempnam('/tmp','getid3'); if(file_put_contents($filename, file_get_contents($url))) { $fileInfo = $getID3->analyze($filename); unlink($filename); print_r($fileInfo); }
이미지 태그에서 src와 alt를 추출하는 방법이다 preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]* alt=[\"']?([^>\"']+)[\"']?[^>]*>/i", $str, $matches); print_r($matches);
아래의 소스대로 배열값에 데이터를 넣어 인코드후 화면에 뿌려주면 된다. 해당 페이지를 저장하면 완성 foreach($rows as $v){ $data[] = array("title"=>$v['title'],"writer"=>$v['writer'],"email"=>$v['email'],"youtube"=>$v['youtube'],"n_date"=>$v['n_date']); } $rst = json_encode($data); header("Pragma: no-cache"); header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate"); header('Content-Type: application/json'); print($rst);
Incorrect string value: '\xF0\x9F\x93\xB201...' for column 'content' 이모티콘 문자열이 있으면 mysql에 저장할 때 위와 같은 오류가 발생한다. 해결방법은 mysql 설정을 변경해야하는데 그게 불가능할 경우 아래 함수를 사용 하여 해당 문자열을 제거한 후 제거하면 된다. function delEmoticon($str) { $rst = preg_replace("/\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}/", "", $str); return $rst; }
여러개의 문자열을 삭제하기 위해 str_replace 를 반복적으로 사용하는 경우가 있는데 아래와 같이 통합할 수 있다. str_ireplace(array("first","second"), "", $str)
$userdb = array( array( 'uid' => '100', 'name' => 'Sandra Shush', 'pic_square' => 'urlof100' ), array( 'uid' => '5465', 'name' => 'Stefanie Mcmohn', 'pic_square' => 'urlof100' ), array( 'uid' => '40489', 'name' => 'Michael', 'pic_square' => 'urlof40489' ) ); 위와 같은 값에서 uid 가 5465 가 있는지 체크하려면 아래와 같이 하면 된다. if(!(array_search('5465', array_column($userdb, 'uid'))===false) ){ echo "있음"; }else{ echo "없음"; }
지정된 시간까지 얼마나 남았는지 시계로 표시해주는 소스입니다. <div id="countdown1"></div> : 년/월/일 계산<br> <div id="countdown2"></div> : 년/월/일 시:분 계산<br> <script> CountDownTimer('4/5/2021', 'countdown1'); CountDownTimer('4/5/2021 1:00 PM', 'countdown2'); function CountDownTimer(dt, id) { var end = new Date(dt); var _second = 1000; var _minute = _second * 60; var _hour = _minute * 60; var _day = _hour * 24; var timer; function showRemaining() { var now = new Date(); var distance = end - now; // 시간 종료 시 뜨는 문구 if (distance < 0
태그안의 특정 속성값을 가져오는 함수 $tag = "<img src='http://test.com/a.jpg' width='100' height='100' /> $width = getTagAttribute($tag, 'width'); //태그안 속성 값 가져오기 function getTagAttribute($tag, $aName) { preg_match( '@'.$aName.'="([^"]+)"@' , $tag, $match); return array_pop($match); }
유튜브 CSV 업로드 시 AD_TYPES 에 대한 설정 By default, YouTube will use your channel defaults (http://www.youtube.com/upload_defaults) to apply ad settings. Use this column to override your defaults for specific ad types. Including an ad type in this column will enable it, and prepending it with an exclamation ('!') will disable it. Omitting an ad format will specify that the channel default is to be used for that ad type. See https://goo.gl/vb30Ck for more information. Valid ad types: "['instream_trueview'
function urlChk(url){ var chkStr=/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/; return chkStr.test(url); }
window.location.href - 현재 페이지의 href (URL) 반환 window.location.hostname - 웹 호스트의 도메인 네임 반환 window.location.pathname - 현재 페이지의 경로와 파일 이름 반환 window.location.protocol - 사용하는 웹 프로토콜 반환 (http:// 혹은 https://)
미설치 사용가능한 jquery 를 이용한 여러가지 차트를 제공하는 사이트이다. 간단한 개인 사용은 무료로 제공하는 것 같다. . https://www.amcharts.com JavaScript Charts & Maps - amCharts JavaScript / HTML5 charts and maps data-viz libraries for web sites and applications. Fast and responsive. WordPress plugin available. Developed since 2006. www.amcharts.com 스택바 차트가 필요해서 샘플 테스트를 해본결과 깔끔하게 나온다. 기능은 더 찾아봐야 겠다 <!-- Styles --> <style> #chartdiv { width: 100%; height: 500px; } </style> <!-- Resources --> <script src="https://cdn.amcharts.com/lib/4/core.
설명이 필요없는 구글 차트이다. 첫 인상은 나쁘지는 않은데 예쁘지는 않다. https://developers.google.com/chart/interactive/docs/gallery/barchart#examples Bar Charts | Google Developers Home Products Charts Guides 이 페이지의 내용 Overview Examples Coloring bars Bar styles Labeling bars Overview Google bar charts are rendered in the browser using SVG or VML , whichever is appropriate for the user's browser. Like all Google charts, bar charts display tooltips when the user hovers over the ... developers.google.com 간단하게 스택바차트를 샘플 테스트 해봤다
td style에 속성을 추가해 주시면 해결됩니다. <td style='mso-number-format:"\@";'>(숫자 데이터)</td> 숫자 천단위 마다 (,)를 찍고자 할때는 이렇게 사용하세요. <td style='mso-number-format:"\#\,\#\#0_;'> (숫자 데이터)</td> mso-number-format:"0" NO Decimals mso-number-format:"0\.000" 3 Decimals mso-number-format:"\#\,\#\#0\.000" Comma with 3 dec mso-number-format:"mm\/dd\/yy" Date7 mso-number-format:"mmmm\ d\,\ yyyy" Date9 mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM" D -T AMPM mso-number-format:"Short Date" 01/03/1998 mso-number-format:"Medium Date
ffmpeg -y -i 소스파일 -vf 'scale=1920x1080' 완료파일 *코덱설정, 8M ffmpeg -i 소스파일 -vcodec libx264 -vf "scale=1920x1080" -b:v 8M 완료파일
파이참에서 모듈 BeautifulSoup 방법 1. 파이참에서 상단 File 메뉴 선택 2. Settings 선택 3. 내 프로젝트 이름>Python Interpreter 선택 4. 화면에 프로젝트에 설치된 모듈이 출력됨 5. + 버튼을 찾을 클릭 > BeautifulSoup 를 검색하여 모듈 선택 후 Install Package 클릭
from urllib.request import urlopen from bs4 import BeautifulSoup try: html = urlopen("https://www.python.co.kr/index.php") bsObj = BeautifulSoup(html.read(), "html.parser") print(bsObj.title) except HTTPError as e: print(e) bsObj.title 은 해당 웹사이트의 title 태그 값을 출력. 다른 태그 값들도 동일한 방법으로 가져올 수 있다. //ID green 을 사용하는 span의 텍스트 가져오기 nameList = bsObj.findAll("span",{"class":"green"}) for name in nameList: print(name.get_text()) //'test' 텍스트가 몇번 나오는지 체크 nameList = bsObj.findAll(text="test") print(len(nameLi
pymysql 을 사용한 mysql 연동방법이다. 당연히 pymysql 을 설치 후 사용해야한다. import pymysql conn = pymysql.connect(host='21.16.6.1', user='user', passwd='pw', db='mysql') cur = conn.cursor() cur.execute("use dbname") * SELECT cur.execute("select * from test_tbl limit 10") if cur.rowcount!=0: rows = cur.fetchall() for row in rows: print(row) else : print("empty") cur.close() conn.close() * INSERT si = "01" gu = "02" so = "03" cur.execute("insert into DB_NAME.tbl (si,gu,so) values (%s,%s,%s)", (si, gu, so)) conn.commit
from urllib.request import urlopen txtPage = urlopen("https://www.test.co.kr/test.txt") print(txtPage.read()) //인코딩시 print(str(txtPage.read(), 'utf-8'))
from urllib.request import urlopen from io import StringIO import csv data = urlopen("http://test.co.kr/test.csv").read().decode('ascii','ignore') dataFile = StringIO(data) csvReader = csv.reader(dataFile) for row in csvReader: print(row)
네이버tv 화면에 표시되는 재생 수를 크롤링하여 가져오기 재생 수는 play 아이디를 사용하는 span 태그안에 있다 from urllib.request import urlopen from bs4 import BeautifulSoup import re try: html = urlopen("https://tv.naver.com/v/24002047/list/67096") bsObj = BeautifulSoup(html.read(), "html.parser") nameList = bsObj.findAll("span", {"class": "play"}) for name in nameList: numbers = re.sub(r'[^0-9]', '', name.get_text()) print(numbers) except HTTPError as e: print(e)
문자열에 들어있는 숫자만 가져오는 방법 import re string = 'aaa1234, ^&*2233pp' numbers = re.sub(r'[^0-9]', '', string) print(numbers)
http://ncov.mohw.go.kr/ 코로나바이러스감염증-19(COVID-19) 코로나바이러스감염증-19 정식 홈페이지로 발생현황, 국내발생현황, 국외발생현황, 시도별발생현황, 대상별 유의사항, 생활 속 거리 두기, 공적마스크 공급현황, 피해지원정책, 홍보자료, FAQ, 관련기관(보건소, 선별진료소 찾기), 정부 브리핑 안내 ncov.mohw.go.kr 사이트에서 확진자수와 사망자수를 크롤링해서 가져오는 방법이다. 일단 해당 숫자는 아래와 같이 표에 입력되어 있다. 해당 표에 id 값이 있으면 가져오기 편할텐데 아쉽게도 id 값이 없어서 남성, 여성 텍스트를 가지고 있는 tr 을 검색했다. from urllib.request import urlopen from bs4 import BeautifulSoup import re try: html = urlopen("http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=1&brdGubun=11") bs
모든 tr 을 가져와 '남성', '여성' 단어가 들어가 있는 tr 만 뽑아오기 nameList = bsObj.findAll("tr") for tr in nameList: chk = tr.find("th",string={"남성","여성"}) if chk!=None: print(tr)
숫자를 크롤링할 경우 보통 쉼표를 포함하고 있는데 이럴 경우 파이썬은 숫자로 인식하지 않아 연산을 할 수 없다. 그럴 경우 아래와 같이 쉼표를 제거해야한다. num = "123,123" print(num.replace(",",""))
아래와 같은 tr 에서 두번 째 td 값을 가져오고 싶을 경우 <tr> <th scope="row">남성</th> <td><span>264,271</span> <span class="txt_clr_nh">(52.48)</span></td> <td><span>2,123</span> <span class="txt_clr_nh">(51.40)</span></td> <td><span class="txt_clr_nh">0.80</span></td> </tr> nameList = bsObj.findAll("tr") for tr in nameList: print(tr.select('td')[1].span.text) 출력값은 2,123 이다.
selenium + chrome 을 사용하기 위한 절차이다. 1. selenium 패키지 설치 2. webdriver-manager 패키지 설치 3. 아래와 같이 소스를 사용하여 현재 OS에 설치된 크롬 브라우저를 사용하도록 세팅 from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.get("https://www.google.com")
구글 뉴스에 들어가서 class 명 DY5T1d 로 되어 있는 타이틀들을 가져오는 소스이다 처음에는 find_element_by_css_selector를 사용했는데 아래와 같은 경고 메세지가 나왔다 DeprecationWarning: find_elements_by_* commands are deprecated 찾아보니 find_elements_by_* 사용하지 말고 find_elements 를 사용하란다 from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.get
By.ID 태그의 id값으로 추출 By.NAME 태그의 name값으로 추출 By.XPATH 태그의 경로로 추출 By.LINK_TEXT 링크 텍스트값으로 추출 By.PARTIAL_LINK_TEXT 링크 텍스트의 자식 텍스트 값을 추출 By.TAG_NAME 태그 이름으로 추출 By.CLASS_NAME 태그의 클래스명으로 추출 By.CSS_SELECTOR css선택자로 추출 from selenium.webdriver.common.by import By driver.find_elements(By.XPATH, '//button[text()="Some text"]') driver.find_elements(By.XPATH, '//button') driver.find_elements(By.ID, 'loginForm') driver.find_elements(By.LINK_TEXT, 'Continue') driver.find_elements(By.PARTIAL_LINK_TEXT, 'Conti') dr
옵션을 주지 않고 실행하면 크롬창이 하나 출력되고 크롤링이 된다. 이 새로운 창을 띄우지 않고 실행하는 방법이다. from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() options.add_argument('headless') options.add_argument('window-size=1920x1080') options.add_argument("disable-gpu") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), chrome_options=options)
selenium 을 사용하여 네이버tv 라이브의 동접자 수를 가져오는 방법이다. from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() options.add_argument('headless') options.add_argument('window-size=1920x1080') options.add_argument("disable-gpu") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), chrome_options=options) driver.get("https:
#특정 문자열 이후 제거 temp = "테스트 문자열 입니다" temp = temp.split("문자열", 1)[0] print(temp) -> 결과 -> 테스트 #특정 문자 제거 temp.replace("문자", "")
<span class="info_append"> 재생수 875,745 <span class="ico_dott">업로드 날짜 : </span><span class="create_time"><span data-date-format data-raw-date="2021-12-17 17:00:00"></span></span> <a href="#none" class="link_fold btn_toggle_info" >자세히</a><!-- 자세히/접기 텍스트 바꿔주세요 --> </span> 위의 재생수가 나오는 부분을 찾아 재생수 숫자만 가져온다 from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager #크롬창을 띄우지 않고
유튜브 조회수를 가져오는 방법은 여러가지가 있다. API를 이용하는 방법도 있고 selenium 를 사용하여 가져오는 방법도 있다. 아래 방법은 페이지 전체를 가져와 자바스크립트 변수인 ytInitialData 를 파싱하여 조회수를 가져오는 방법이다. ytInitialData 변수에는 json 데이터가 들어가 있다. import requests import re import json try: html = requests.get("https://www.youtube.com/watch?v=T5cHCXeweYo").text matched = re.search(r'var ytInitialData = (.*?)};', html, re.S) json_string = matched.group(1) + "}" # json을 output_list에 삽입 output_list = json.loads(json_string) print(output_list['contents']['twoColumnWatc
pafy는 유튜브 정보를 손쉽게 가져올수 있도록 만든 라이브러리이다. . https://pythonhosted.org/pafy/ Pafy Documentation — pafy 0.5.1 documentation pafy 0.5.1 Pafy Documentation API Keys Pafy Objects and Stream Objects Pafy Objects Pafy Attributes Pafy Methods Stream Lists Stream Objects Stream Attributes Stream Methods Stream.download() example Playlist Retrieval pafy.get_playlist() example Playlist Attributes Docs » Pafy Documentation View pa... pythonhosted.org 윈도우 + 파이참 환경에서 테스트 했는데 pafy를 설치하니 youtube-dl이 필요하다는 메세지가 나와 패
자바스크립트로 모바일 접속여부 체크하는 함수이다. 모바일로 접속하면 true를 리턴한다. function mobileChk(){ var agent = window.navigator.userAgent; const mobileRegex = [ /Android/i, /iPhone/i, /iPad/i, /iPod/i, /BlackBerry/i, /Windows Phone/i] return mobileRegex.some(mobile => agent.match(mobile)); }
파이썬, selenium 을 사용하여 네이버 기사의 댓글을 가져오는 소스이다. 1. 네이버 기사 페이지 오픈 2. 댓글 더보기 클릭 3. 클린봇 해제 (모든 댓글을 볼 수 있도록 설정) 4. 마지막 댓글이 나올때까지 더보기 클릭 5. 기사제목, 시간, 성비, 연령대 추출 5. 댓글 추출 from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager import time url = "https://news.naver.com/main/read.naver?mode=LSD&mid=shm&sid1=100&oid=015&aid=0004648342" driver = webdriver.Chrome(service=Service(Chr
PHP를 이용하여 네이버 기사리스트를 크롤링 하는 소스이다. 가져온 HTML 은 simplehtmldom 을 사용하여 파싱하였다. 페이지를 지정하여 원하는 페이지까지 크롤링 할 수 있다. include_once './_simplehtmldom/simple_html_dom.php'; $ePage = 3; $url = "https://news.naver.com/main/list.naver?mode=LSD&mid=sec&sid1=001&date=20220104&page="; $html = new simple_html_dom(); for($i=1;$i<=$ePage;$i++){ $temp = get_content("{$url}{$i}"); if(!$temp) break; $html->load($temp); //상단 10개 기사 if($html->find('ul[class=type06_headline]',0)){ foreach($html->find('ul[class=type06_headlin
디데이 날짜 표시를 위한 소스이다. $end_date = date('2022-03-09'); //디데이 날짜 $d_day = floor((strtotime(substr($end_date,0,10)) - strtotime(date('Y-m-d')))/86400); if($d_day>=0) echo "D-{$d_day}";
가장 인기 좋고 성능 좋은 웹에디터 * 기본 세팅 소스 <script src="/_ckeditor/build/ckeditor.js"></script> <textarea id="ckeditor" name="content" class="txtarea"></textarea> <script> ClassicEditor .create( document.querySelector( '#ckeditor' ), { //툴바 옵션 toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', 'blockQuote', 'insertTable', 'mediaEmbed', 'undo', 'redo' ], //---------------------------------------------------------------- heading: { options: [ { mo
ckeditor5의 툴바에 원하는 메뉴를 세팅하고 싶다면 먼저 홈페이지에 들어가 원하는 기능을 세팅하여 빌드하여 다운로드 하여야한다. 주소는 아래와 같은데 진행은 어렵지 않다. 원하는 기능들을 선택 후 쭉~ 진행하고 다운로드 받으면된다. 물론 유료기능들은 돈을 지불해야한다. 이렇게 빌드하지 않고 기본 버전에 기능을 넣으면 지원하지 않는 기능이라고 나온다. https://ckeditor.com/ckeditor-5/online-builder/ CKEditor 5 Online Builder | Create your own editor in 5 steps Create your own CKEditor 5 build with customized plugins, toolbar and language in 5 simple steps. ckeditor.com 아래는 툴바에 원하는 메뉴들을 넣어본 소스이다. ClassicEditor .create( document.querySelector( '#cke
select sum( if (month>='01' and month <'04' , 1, 0) ) as msum from test if ( 조건, 참일경우 값, 거짓일 경우 값) 예) SELECT a.*, SUM( if(b.reg_date>='2022-01-01' AND b.reg_date<'2022-01-31', b.score, 0) ) AS score1, SUM( if(b.reg_date>='2022-01-01' AND b.reg_date<'2022-04-01', b.score, 0) ) AS score2, SUM( if(b.reg_date>='2022-01-01' AND b.reg_date<'2023-01-01', b.score, 0) ) AS score3 FROM USER_ACCOUNT a LEFT OUTER JOIN USER_SCORE b ON a.user_id=b.user_id
ckeditor에서 이미지 업로드 처리하는 방법이다. - myuploader.js : ckeditor 와 연동할 파일 - imgUploadProc.php : myuploader.js 에서 호출되어 이미지를 서버에 업로드 처리할 파일 [ckeditor 페이지 세팅 샘플] -------------------------------- <script src="/_ckeditor5/build/ckeditor.js"></script> <script src="/_ckeditor5/myuploader.js"></script> <textarea id="ckeditor" name="ckeditor" class="txtarea"></textarea> <script> ClassicEditor .create( document.querySelector( '#ckeditor' ), { //툴바 옵션 toolbar: { items : ['fontFamily', 'fontSize', 'fontColor', 'fon
에디터의 높이를 설정하는 방법 }).then(function(editor) { //높이를 480으로 지정 - 높이고정 //입력이 480을 넘으면 스크롤이 생김 $('style').append('.ck-content { height: 480px; }'); objEditor = editor; //최소 높이를 480으로 지정 - 높이 가변 //입력이 480을 넘으면 높이가 늘어남 $('style').append('.ck-content { min-height: 480px; }'); }).catch( error => { console.log( error ); } );
ckeditor5 media embed 에서 네이버tv 주소를 넣었을 경우 글에 삽입되도록 처리하는 방법이다. 기본적으로 해외 서비스인 유튜브, 데일리보션 같은거는 처리가 되는데 네이버tv는 당연히 수동으로 처리해줘야 한다. 네이버tv 주소형식 2가지를 받아 iframe 형식으로 만들어 리턴해주는 설정이다 ClassicEditor .create( document.querySelector( '#ckeditor' ), { toolbar: { items : ['mediaEmbed'], shouldNotGroupWhenFull: true, }, mediaEmbed: { previewsInData: true, providers: [ { name: 'navertv', url: [/tv\.naver\.com\/v\/(\w+)/, /tv\.naver\.com\/embed\/(\w+)/], html: match => { const id = match[ 1 ]; return ( '<div style=
ckeditor5 media embed 에서 카카오tv 주소를 넣었을 경우 글에 삽입되도록 처리하는 방법이다. 주소형식 2가지를 받아 iframe 형식으로 만들어 리턴해주는 설정이다 ClassicEditor .create( document.querySelector( '#ckeditor' ), { toolbar: { items : ['mediaEmbed'], shouldNotGroupWhenFull: true, }, mediaEmbed: { previewsInData: true, providers: [ { name: 'kakaotv', url: [/^tv\.kakao\.com\/v\/([\w-]+)/, /^tv\.kakao\.com\/channel\/[^/]+\/cliplink\/(\d+)/], html: match => { const id = match[ 1 ]; return ( '<div style="position: relative; padding-bottom: 100%; hei
mysql 8버전에서는 password 함수를 지원하지 않는다. * php 함수로 대체 function mysql_password($var){ $rst = '*'.strtoupper(sha1(sha1($var, true))); return $rst; } * mysql 쿼리로 대체 . select CONCAT('*', UPPER(SHA1(UNHEX(SHA1(('암호')))))) as password
ckeditor5 에서 허용태그 세팅방법은 아래 사이트를 참조 https://ckeditor.com/docs/ckeditor5/latest/features/general-html-support.html General HTML Support - CKEditor 5 Documentation Learn how to install, integrate and configure CKEditor 5 Builds and how to work with CKEditor 5 Framework, customize it, create your own plugins and custom editors, change the UI or even bring your own UI to the editor. API reference and examples included. ckeditor.com 아래는 모든 태그를 허용하는 세팅이다. ClassicEditor .create( document.querySelector(
window.parent.location.reload(); // 부모창 새로고침 window.parent.location.href = url; //url 입력
iframe 안을 클릭했을 때 이벤트 처리방법 <!doctype html> <html lang="en"> <!DOCTYPE html> <html> <head> <title></title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> var detector = setInterval(function() { var elem = document.activeElement; if (elem && elem.tagName == 'IFRAME') { alert("iframe click"); clearInterval(detector); } }, 100); </script> </head> <body> <iframe id='' src='https://tv.naver.com/embed/25698159?autoPlay=true' frameborder='no' scrollin
* 최대 넓이 설정 }).then(function(editor) { . $('style').append('.ck-editor { max-width : 320px;}'); }).catch( error => { console.log( error ); } ); * css 로 설정하기 <style> .ck.ck-editor{ max-width: 500px; } </style>
jquery로 ajax 사용하는 샘플이다. $.ajax({ url : 'page.php', //연동페이지 주소 type : 'get', // 요청방식 (get/post) // data : {'name' : name}, // 전송 데이터 사용시(없으면 생략가능) success : function(html){ alert('연동성공='+html); }, error : function(){ alert('연동실패처리'); } })
select 한 결과 값을 바로 insert 하기위한 쿼리이다. insert into tbl1 (c1, c2, c3) select 'test', c4, c5 from tbl2 where c6='test' limit 5; tbl2의 c6가 test 인 5개 리스트를 tbl1에 iinsert 한다