728x90

날짜를 증가시키면서 반복하는 스크립트

#!/bin/bash
 
# 시작 날짜 설정
#current_date=$(date +%Y%m%d)
current_date="20240131"
echo "현재 날짜: $current_date"
 
# 반복 횟수 설정
num_days=55
 
# 날짜 증가 반복
for (( i=0; i<$num_days; i++ )); do
    # 현재 날짜 출력
    echo "현재 날짜: $current_date"
 
    # 다음 날짜 계산
    next_date=$(date -"$current_date + 1 days" +%Y%m%d)
    echo "다음 날짜: $next_date"
 
    # 그다음 날짜 계산
    next_next_date=$(date -"$current_date + 2 days" +%Y%m%d)
    echo "그다음 날짜: $next_next_date"
 
    unzip ${next_date}_dailynoticedata.zip
    mv AlterD.JUSUBM.${next_next_date}.TI_SPBD_BULD.TXT ${next_next_date}_BULD.cvs
 
    # 다음 반복을 위해 현재 날짜 업데이트
    current_date=$next_date
done
 
rm -*.TXT
rm -*.zip

 

 

'리눅스' 카테고리의 다른 글

CentOS 7 PHP 7.4 MariaDB 10.5 설치  (0) 2022.05.14
CentOS 5.8 APM 설치 과정  (0) 2022.05.14
VMWare Network 설정  (0) 2022.04.23
CentOS 7 Jenkins 설치  (0) 2022.03.25
Apache log Full  (0) 2022.02.22
블로그 이미지

Link2Me

,
728x90

윈도우즈 환경에서 잘 동작하던 코드가 리눅스(CentOS 7) 환경에서 테스트하니까 동작이 안된다.

아래와 같이 설정하면 제대로 동작되는 걸 확인할 수 있다.

 

1. Google Chrome 설치

yum -y install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

 

2. Chrome Driver 설치

먼저 google-chrome --version 을 실행하여 현재 버전을 확인한다.

 

wget https://storage.googleapis.com/chrome-for-testing-public/123.0.6312.58/linux64/chromedriver-linux64.zip
로 파일을 다운로드 한다.

 

압축을 풀고 chromedriver 파일을 아래와 같이 옮긴다. (이게 중요하더라)

mv chromedriver /usr/bin/

 

3. 이제 코드 상에서 동작되도록 구현된 코드를 살펴보자.

chromedriver 를 /usr/bin 으로 옮겨서

driver = webdriver.Chrome(options=options) 만으로 코드가 잘 동작된다.

구글링해보면 아래와 같은 설정으로 동작이 되는 것처럼 설명되어 있지만...

driver = webdriver.Chrome(
    executable_path='크롬드라이버 설치경로', options=options
)

로 테스트 한 것은 동작이 안되었다.

 

pip install selenium 을 하면 4.18.1 버전이 설치된다. (pip list 로 확인)

# pip install selenium  
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
 
import time
 
def jusoGet(keyword):
    # 크롬 드라이버 생성
    options = Options()
    options.add_argument("headless"# 창 숨기는 옵션
    options.add_argument("--no-sandbox")
    driver = webdriver.Chrome(options=options)
    #driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
 
    # 사이트 접속하기
    url = 'https://www.juso.go.kr/support/AddressMainSearch.do?searchKeyword='
    driver.get(url+keyword) # url 페이지로 이동
    time.sleep(2# 로딩 대기
 
    try:
        h = driver.find_element(By.XPATH, value='//*[@id="list1"]/div[2]/span[2]').text
        print(h)
    except:
        pass
 
 
if __name__ == "__main__":
    keyword = '서초구청'
    jusoGet(keyword)

 

 

Python3.9 버전이 설치된 환경 변수 설정 방법

1. Python 환경변수 3.9 설정 (alias)
vi /etc/profile
 
alias python3='/usr/local/bin/python3.9'
alias python='/usr/local/bin/python3.9'
alias pip='/usr/local/bin/pip3.9'
 
source /etc/profile
 
2. 설치 확인
python
python3 -V

 

 

Python 3.9 버전과 3.11 버전 모두 정상 동작함을 확인했다.

 

 

블로그 이미지

Link2Me

,
728x90

오랫만에 크롤링을 해보려고 하니까 selenium 드라이브 설치없이 auto 로 설정하는 옵션이 전혀 동작하지 않는다.

버전업이 중단되어서 동작이 안되는가 보다.

방식이 새롭게 변경되었다는 걸 검색하고 테스트 해본 결과 확인했다.

 

아래 코드를 CentOS 7 에서 실행해보니 안된다. Windows10 환경에서는 잘 된다.

CentOS 7 환경에서 성공한 사항은 다음 게시글에 기록해둔다.

# pip install -U selenium  # Selenium is upgraded to v4.0.0
# pip install webdriver-manager  # Webdriver Manager for Python is installed
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
 
import time
 
def jusoGet(keyword):
    # 크롬 드라이버 생성
    options = Options()
    #options.add_experimental_option("detach", False) # 브라우저 창 떳다기 사라지기(False), 계속 유지(True)
    options.add_argument("headless"# 창 숨기는 옵션
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    # driver.maximize_window() # 브라우저 창 최대로 하는 옵션인데 필요없을 거 같다.
 
    # 페이지 로딩이 완료될 때 까지 기다리는 코드
    driver.implicitly_wait(1)
 
    # 사이트 접속하기
    url = 'https://www.juso.go.kr/support/AddressMainSearch.do?searchKeyword='
    driver.get(url+keyword) # url 페이지로 이동
    time.sleep(2# 로딩 대기
 
    try:
        h = driver.find_element(By.XPATH, value='//*[@id="list1"]/div[2]/span[2]').text
        print(h)
    except:
        pass
 
 
if __name__ == "__main__":
    keyword = '서초구청'
    jusoGet(keyword)

 

 

 

크롬 브라저에 맞는 driver 설치방법 → 불필요

드라이버 설치하고 해보면 아래와 같은 경고 문구가 나온다.

DeprecationWarning: executable_path has been deprecated, please pass in a Service object

 

아래 내용은 불필요한 사항이지만 나중에 보면서 이런 적도 있었구나 하는 셈치고 적어둔다.

chrome://settings/help 를 크롬 브라우저에서 실행하여 현재 버전을 찾아야 한다.

 

 

https://chromedriver.chromium.org/downloads/version-selection

 

ChromeDriver - WebDriver for Chrome - Version Selection

Version selection is the process of matching a Chrome binary of a given version to a compatible ChromeDriver binary. For versions 115 and newer Starting with M115 the ChromeDriver release process is integrated with that of Chrome. The latest Chrome + Chrom

chromedriver.chromium.org

사이트에 접속하면 최신버전과 맞지 않는다.

 

더 최신버전을 위에서 찾아들어가야 한다.

https://googlechromelabs.github.io/chrome-for-testing/

 

Chrome for Testing availability

chrome-headless-shellmac-arm64https://storage.googleapis.com/chrome-for-testing-public/123.0.6312.58/mac-arm64/chrome-headless-shell-mac-arm64.zip200

googlechromelabs.github.io

 

 

블로그 이미지

Link2Me

,
728x90

주소(juso.go.kr) 사이트에서 파일을 다운로드 받아서 주소를 만들고 파싱처리를 하다보니 이런 데이타가 있더라.

 

대부분은 지번주소가 존재하는데 신규로 생성되는 도로명주소에 해당하는 지번주소가 없는 것이다.

이런 데이터는 Naver Map API 에 위치좌표를 조회하면 결과가 없는 경우가 있다.

그렇다고 구글 Geocording API 를 연동하여 처리를 하자니 건당 비용이 발생해서 못하겠다.

불편하지만 구글 스프레드시트를 통해서 자료를 업데이트하는 수 밖에...

방법을 좀 더 찾아봐야겠다.

 

 

 

블로그 이미지

Link2Me

,
728x90

Javascript 코드를 구현할 때 재귀호출을 하면서 Identifier 'marker' has already been declared 라는 메시지가 나온다.

뭐가 문제일까?

 

아래코드를 새로운 창에서 매번 실행한다면 문제될 것이 전혀 없다.

그리고 var 변수로 선언된 변수는 다시 선언해도 되므로 문제가 되지 않는다.

즉, 특정 div 영역에 재로딩을 해도 var 변수가 덮어쓰기 되므로 문제될 것이 없다.

하지만 변수를 let, const  로 변경하면 문제가 될 수 있다.

<body>
<div id="map" style="width:100%;height:350px;"></div>
 
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=발급받은 APP KEY를 사용하세요"></script>
<script>
var mapContainer = document.getElementById('map'), // 지도를 표시할 div 
    mapOption = { 
        center: new kakao.maps.LatLng(33.450701126.570667), // 지도의 중심좌표
        level: 3 // 지도의 확대 레벨
    };
 
var map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
 
// 마커가 표시될 위치입니다 
var markerPosition  = new kakao.maps.LatLng(33.450701126.570667); 
 
// 마커를 생성합니다
var marker = new kakao.maps.Marker({
    position: markerPosition
});
 
// 마커가 지도 위에 표시되도록 설정합니다
marker.setMap(map);
 
// 아래 코드는 지도 위의 마커를 제거하는 코드입니다
// marker.setMap(null);    
</script>
</body>

 

 

아래와 같이 코드를 구현했을 경우에는 어떤 문제가 생기는지 살펴보자.

id가 panel_content 라는 DIV 영역에 필요한 파일을 계속 Load하여 화면을 새로 그리는 구조로 코드를 구현해서 사용하고 있다.

<main>
    <div class="container-fluid text-center">
        <div class="row">
            <div class="col-md-12">
                <div class="content" id="panel_content">
                </div>
                <div class="card">
                </div>
            </div>
        </div>
    </div>
</main>
 
<script>
function MListTable(where,keyword,curPage,uri,bidx,sort,cat1,cat2,idx) {
 
    if (keyword.length > 20) {
        calluri = uri + '?p='+curPage+'&idx='+idx+'&cat1='+cat1+'&cat2='+cat2+'&where='+where+'&keyword='+encodeURIComponent(keyword)+'&sortby='+sort;
        console.log('bCode : ' + calluri);
    }
    else
        calluri = uri + '?p='+curPage+'&idx='+idx+'&cat1='+cat1+'&cat2='+cat2+'&where='+where+'&keyword='+encodeURIComponent(keyword)+'&bidx='+bidx+'&sortby='+sort;
 
    $('#panel_content').load(calluri, function() {
        var curPage = $('#paging .act a').text();
 
 
        $('#MNListTable tbody tr').mouseover(function() {
            $(this).children().css({
                'backgroundColor' : '#DCDCDC''cursor' : 'pointer'
            });
        }).mouseout(function() {
            $(this).children().css({
                'backgroundColor' : '#FFFFFF''cursor' : 'default'
            });
        });
 
        $('#MNListTable tbody tr').click(function() {
            var idx = $(this).attr('id');
            MNView(idx,curPage,where,keyword,cat1,cat2,bidx,sort);
        });
        $('#MNHome').click(function(e) {
            e.preventDefault();
            var uri = $('#urlPath').attr('url-path');
           MListTable('','',1,uri,'','','','','');
        });
 
    });
}
 
</script>

 

 

테이블에서 특정 TR 를 누르면 해당 값을 읽어서 MNView 로 넘기는 형태이다.

<script>
function MNView(idx,curPage,where,keyword,cat1,cat2,bidx,sort){
    var uri = 'View.php';
   MListTable(where,keyword,curPage,uri,bidx,sort,cat1,cat2,idx);
}
</script>

 

 

id 가 panel_content 의 DIV 영역에 View.php?idx=1 파일의 내용을 로딩하게 된다.

아래 파일이 View.php?idx=3 으로 다시 로딩하게 되면 let marker 가 이미 선언되어 있기 때문에 중복 선언되는 문제가 발생하는 것이다.

<div class="card">
<div class="mt-1 mb-2 mx-2">
    <div id="map" style="width:100%;height:450px;"></div>
</div>
</div>
 
<script>
var latitude = '<?php echo $lat;?>';
var longitude = '<?php echo $lng;?>';
 
// 마커를 담을 배열입니다
let marker = [];
 
const mapContainer = document.getElementById('map'), // 지도를 표시할 div 
    mapOption = { 
        center: new kakao.maps.LatLng(latitude, longitude), // 지도의 중심좌표
        level: 6 // 지도의 확대 레벨
    };
 
const map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
 
// 마커가 표시될 위치입니다 
const markerPosition  = new kakao.maps.LatLng(latitude, longitude); 
 
// 마커를 생성합니다
marker = new kakao.maps.Marker({
    position: markerPosition
});
 
// 마커가 지도 위에 표시되도록 설정합니다
marker.setMap(map);
 
// 아래 코드는 지도 위의 마커를 제거하는 코드입니다
// marker.setMap(null); 
</script>

 

 

이 문제를 방지하려면 함수를 만들어서 구현하면 해결된다.

index.php 파일 하단에 DrawMap 함수를 추가한다.

<script>
function DrawMap(latitude,longitude){
    // 마커를 담을 배열입니다
    let marker = [];
 
    const mapContainer = document.getElementById('map'), // 지도를 표시할 div 
        mapOption = { 
            center: new kakao.maps.LatLng(latitude, longitude), // 지도의 중심좌표
            level: 6 // 지도의 확대 레벨
        };
 
    const map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
 
    // 마커가 표시될 위치입니다 
    const markerPosition  = new kakao.maps.LatLng(latitude, longitude); 
 
    // 마커를 생성합니다
    marker = new kakao.maps.Marker({
        position: markerPosition
    });
 
    // 마커가 지도 위에 표시되도록 설정합니다
    marker.setMap(map);
 
    // 아래 코드는 지도 위의 마커를 제거하는 코드입니다
    // marker.setMap(null); 
    
</script>

 

그리고 View.php 파일은 아래와 같이 수정한다.

그러면 let 과 const 로 선언한 변수가 재선언되지 않기 때문에 문제가 해결된다.

<div class="card">
<div class="mt-1 mb-2 mx-2">
    <div id="map" style="width:100%;height:450px;"></div>
</div>
</div>
 
<script>
var latitude = '<?php echo $lat;?>';
var longitude = '<?php echo $lng;?>';
 
DrawMap(latitude,longitude);
</script>

 

블로그 이미지

Link2Me

,