코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
public class String_1 {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String x = new String("JAVA");
        String y = x + "Program";
        System.out.println("x = " + x);
        System.out.println("y = " + y);
        
        int x2length;
        char x2char;
        String x2 = "Java Program";
        x2length = x2.length();
        x2char = x2.charAt(2);
        System.out.println("char at index of x : " + x2char);
        System.out.println("Length of x is " + x2length);
        
        String str = new String("string are standard objects");
        String strx = new String("sta");
        System.out.println("char's index = " + str.indexOf('r'));
        System.out.println("the first position of strx in str = " + str.indexOf(strx));
    }
 
}
 
cs

 

실행결과:

설명: 

 String x = new String("JAVA");

 String y = x + "Program";

String객체 생성

 

x2length = x2.length();

length()함수를 이용하여 x2의 길이 반환.

 

x2char = x2.charAt(2);

charAt()함수를 이용하여 2번째 인덱스에 위치한 값 반환.

 

str.indexOf('r')

indexOf()함수를 이용하여 r이 몇번 인덱스에 위치하는지 반환.

 

 

 

'Java' 카테고리의 다른 글

Java, 클래스 생성  (0) 2019.10.04
Java, String(2)  (0) 2019.10.04
Java, Interger.parseInt(), 예외처리  (0) 2019.09.25
Java, Array  (0) 2019.09.25
Java, for-while, continue, Scanner  (0) 2019.09.25

한국 거래소에 올라와 있는 엑셀파일을 다운받는 것을 구현해보았다.

 

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import requests
import pandas as pd
from io import BytesIO
 
def get_Excel(tdate):
    gen_req_url = "http://marketdata.krx.co.kr/contents/COM/GenerateOTP.jspx"
    query_str_params = {
        'name''fileDown',
        'filetype''xls',
        'url''MKD/13/1302/13020402/mkd13020402',
        'market_gubun''ALL',
        'lmt_tp''1',
        'sect_tp_cd''ALL',
        'schdate': tdate,
        'pagePath''/contents/MKD/13/1302/13020402/MKD13020402.jsp'
    }
    r = requests.get(gen_req_url, query_str_params)
    gen_req_url = 'http://file.krx.co.kr/download.jspx'
    headers = {
        'Referer''http://marketdata.krx.co.kr/mdi'
    }
    form_data = {
        'code': r.content
    }
    r = requests.post(gen_req_url, form_data, headers=headers)
    r.content
    df = pd.read_excel(BytesIO(r.content))
    file_dir = "E:/3_2/python/Crawlling/data/"
    file_name = str(tdate)+'.xls'
    df.to_excel(file_dir + file_name)
    print(tdate, " crawlling")
    return
 
for year in range(2018,2019):
    for month in range(1,13):
        for day in range(1,32):
            tdate = year * 10000 + month * 100 + day * 1
            if tdate <= 20191002:
                get_Excel(tdate)
cs

 

실행결과 :

다운받아지는 모습이다.

엑셀파일 모습이다.

 

 

수정 전

 

 

코드 :

1
2
3
4
5
6
7
from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\JW\Desktop\chromedriver_win32\chromedriver.exe")
driver.get("https://www.hansung.ac.kr/web/www/login")
driver.find_element_by_name('_58_login').send_keys('1433047')
driver.find_element_by_name('_58_password').send_keys('')
driver.find_element_by_class_name('btn_login').click()
 
cs

 

실행결과 : 안됨.

================= RESTART: C:\Users\JW\Desktop\python\1-1.py =================
Traceback (most recent call last):
  File "C:\Users\JW\Desktop\python\1-1.py", line 6, in 
    driver.find_element_by_class_name('btn_login').click()
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".btn_login"}
  (Session info: chrome=77.0.3865.90)

 

 

수정 후

 

 

 

코드 :

1
2
3
4
5
6
7
8
from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\JW\Desktop\chromedriver_win32\chromedriver.exe")
driver.get("https://www.hansung.ac.kr/web/www/login")
driver.find_element_by_name('_58_login').send_keys('1433047')
driver.find_element_by_name('_58_password').send_keys('')
driver.find_element_by_xpath("""//*[@id="loginUnited"]/form/input[7]""").click()
 
 
cs

 

실행결과 : 로그인 성공

 

설명 : 

from selenium import webdriver

selenium모듈을 이용할 것이다.

 

driver = webdriver.Chrome(r"C:\Users\JW\Desktop\chromedriver_win32\chromedriver.exe")

크롬의 웹드라이버를 가져와 driver라는 변수에 저장.

 

driver.get("https://www.hansung.ac.kr/web/www/login")

get()함수를 이용하여 매개변수로 받은 url주소를 가져온다.

 

페이지에 들어가 검사를 통해서 id박스에 해당하는 곳을 확인했다. id가 있으니 iname으로 받아온다.

driver.find_element_by_name('_58_login').send_keys('1433047')

find_element_by_name()함수를 이용하여 id가 매개벼수인 곳을 찾고 .send_keys()함수를 이용하여 그 곳에 매개벼수를 입력해주었다.

 

driver.find_element_by_name('_58_password').send_keys('')

비밀버호도 동일하게 코딩

 

driver.find_element_by_xpath("""//*[@id="loginUnited"]/form/input[7]""").click()

수정 전에 실패했던 내용이다. find_element_by_xpath()함수를 이용하여 버튼을 찾고 click()함수를 통해서 클릭을 해준다.

xpath를 받아오는법은 

이렇게 받아오면

//*[@id="loginUnited"]/form/input[7]  이런게 복사가 된다

이 것을 이유는 모르겠지만 ''' ''' (따움표 3개씩)안에 넣어주면 된다.

 

 

 

코드 : 

1
2
3
4
5
6
7
8
9
import bs4
import urllib.request
url = "http://naver.com"
html = urllib.request.urlopen(url)
bsobj = bs4.BeautifulSoup(html, "html.parser")
realtime_hotkeyword = bsobj.find_all("span", {"class":"ah_k"})
for keyword in realtime_hotkeyword:
    print(keyword.text)
 
cs

 

실행결과 :

 

설명 : 

import bs4

import urllib.request

bs4와 request모듈을 사용한다.

 

url = "http://naver.com"

html = urllib.request.urlopen(url)

urllib.request.urlopen()함수를 이용하여 url을 html이라는 변수에 저장했다.

 

bsobj = bs4.BeautifulSoup(html, "html.parser")

bs4.BeautifulSoup(매개변수, "html.parser") 함수를 통하여 파싱을 하고 bsobj라는 변수에 저장했다. 현재에는 해당 페이지의 모든 html문서가 저장되어있는 상황. print(bsobj)로 확인가능.

 

realtime_hotkeyword = bsobj.find_all("span", {"class":"ah_k"})

인기검색어에 해당하는 곳을 찾아보면 span태그안에 class 이름이 정해져있는 것을 알 수 있다.bsobj.find_all()함수를 이용하여 인기검색어들을 realtime_hotkeyword이라는 변수에 저장.

 

for keyword in realtime_hotkeyword:

    print(keyword.text)

for문을 이용하여 모두 출력.

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import turtle
= turtle.Turtle()
t.speed(50)
t.up()
t.goto(0,-200)
t.down()
t.fillcolor("red")
t.begin_fill()
t.circle(250)
t.end_fill()
= 50;
t.up()
t.goto(0,-100 - x)
t.down()
t.fillcolor("white")
t.begin_fill()
t.circle(200)
t.end_fill()
t.up()
t.goto(0,-50-x)
t.down()
t.fillcolor("red")
t.begin_fill()
t.circle(150)
t.end_fill()
t.up()
t.goto(0,0-x)
t.down()
t.fillcolor("blue")
t.begin_fill()
t.circle(100)
t.end_fill()
t.up()
t.goto(-85,70-x)
t.fillcolor("white")
t.begin_fill()
= 170
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.end_fill()
 
cs

 

실행결과:

 

설명:

= turtle.Turtle()

turtle객체의 메소드인 Turtle()함수를 이용하여 trutle을 생성 후 변수 t에 저장.

 

t.speed(50)

t의 그리기 속도

 

t.up()

up()함수를 이용하여 t를 도화지에서 뗀다(?) : 그려지지 않음.

 

t.goto(0,-200)

해당 좌표로 이동

 

t.down()

down()함수를 이용하여 t를 도화지에 다시 붙인다. : 그려짐

 

t.fillcolor("red")

fillcolor()함수를 이용해서 빨간색으로 칠할 준비

 

t.begin_fill()

begin_fill()함수를 이용해서 색칠 시작

 

t.circle(200)

circle()함수를 이용해서 반지름이 200인 원 그리기

 

t.end_fill()

end_fill()함수를 이용해서 색칠 끝

 

 

 

Javascript의 Object 생성 방법은 세 가지가 있다

  1. new Object()이용
  2. 리터럴 표기법
  3. 프로토타입
  1. new Object()이용
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <html>
        <head>
            <title></title>
            <meta charset="utf-8">
            <script>
                function deposit(a) {return this.balance += a;}
                function withdraw(a) {return this.balance -= a;}
     
            </script>
        </head>
        <body>
            <h3>new Object()</h3>
            <hr>
            <script>
                var account = new Object();
                account.owner = 'KSD';
                account.code = '1111';
                account.balance = 400000;
                account.deposit = deposit;
                account.withdraw = withdraw;
     
                account.deposit(10000);
                document.write('after deposit balance = ' + account.balance + '<br>');
                account.withdraw(20000);
                document.write('after deposit withdraw = ' + account.balance + '<br>');
            </script>
        </body>
    </html>
    cs
  2. 리터럴 표기법
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <html>
        <head>
            <title></title>
            <meta charset="utf-8">
        </head>
        <body>
            <h3>new Object()_Literal</h3>
            <hr>
            <script>
                var account = {
                owner : 'KSD',
                code : '1111',
                balance : 400000,
                deposit : function deposit(a) {return this.balance += a;},
                withdraw : function withdraw(a) {return this.balance -= a;}
                }
     
                account.deposit(10000);
                document.write('after deposit balance = ' + account.balance + '<br>');
                account.withdraw(20000);
                document.write('after deposit withdraw = ' + account.balance + '<br>');
            </script>
        </body>
    </html>
    cs
  3. 프로토타입
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <html>
        <head>
            <title></title>
            <meta charset="utf-8">
        </head>
        <script>
            function Account(owner, code, balance){
     
                this.owner = owner;
                this.code = code;
                this.balance = balance;
                this.deposit = function deposit(a) {return this.balance += a;}
                this.withdraw = function withdraw(a) {return this.balance -= a;}
     
            }
        </script>
        <body>
            <h3>new Object()_Prototype</h3>
            <hr>
            <script>
                var account = new Account('KSD''1111'40000);
            account.deposit(10000);
            document.write('after deposit balance = ' + account.balance + '<br>');
            account.withdraw(20000);
            document.write('after deposit withdraw = ' + account.balance + '<br>');
            </script>
        </body>
    </html>
    cs

     

실행결과 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package exception;
 
public class exception_Num {
    public static void main(String[] args) {
        String[] strNum = {"23""12""3.14""998"};
        
        int i = 0;
        try {
            for(i = 0; i < strNum.length; i++) {
                int j = Integer.parseInt(strNum[i]);
                System.out.println(j);
            }
        }
        catch(NumberFormatException e) {
            System.out.println(strNum[i] + "는 정수로 변환할 수 없습니다");
        }
    }
}
 
cs

NumberFormatException 예외처리를 하는 코드이다. 

Integer.parseInt()라는 함수도 볼 수 있다. String 을 int로 변환하는 코드이다.

 

'Java' 카테고리의 다른 글

Java, String(2)  (0) 2019.10.04
Java, String(1)  (0) 2019.10.04
Java, Array  (0) 2019.09.25
Java, for-while, continue, Scanner  (0) 2019.09.25
Java, switch문  (0) 2019.09.25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
public class Review_Array {
 
    static int[][] makeArray(){
        int intArr[][] = new int[4][];
        for(int x = 0; x < intArr.length; x++) {
            intArr[x] = new int[6-x];
        }
 
        for(int i = 0; i < intArr.length; i++) {
            for(int j = 0; j < intArr[i].length; j++) {
                intArr[i][j] = (i + 1)*10 + j;
            }
        }
        return intArr;
    }
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int intArr[][];
        intArr = makeArray();
        for(int i = 0; i < intArr.length; i++) {
            for(int j = 0; j < intArr[i].length; j++) {
                System.out.print(intArr[i][j] + " ");
            }
            System.out.println();
        }
    }
 
}
cs

method makeArray에서 비정방형 2차원 배열을 생성한뒤 main함수에서 호출하는 코드이다.

 

실행결과 : 

10 11 12 13 14 15 
20 21 22 23 24 
30 31 32 33 
40 41 42 

'Java' 카테고리의 다른 글

Java, String(2)  (0) 2019.10.04
Java, String(1)  (0) 2019.10.04
Java, Interger.parseInt(), 예외처리  (0) 2019.09.25
Java, for-while, continue, Scanner  (0) 2019.09.25
Java, switch문  (0) 2019.09.25

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package For_While_;
 
import java.util.Scanner;
 
public class ContinueEx {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int sum = 0;
        int i = 0;
        while(i < 5) {
            i++;
            int n = sc.nextInt();
            if(n <= 0)continue;
            sum+=n;
        }
        System.out.println(sum);
        sc.close();
    }
 
}
cs
5개의 값을 받으면서 양수들만의 합을 구하는 코드이다.
while문안의 if문에서 n이 0이하일때는 바로 continue를 함으로써 sum에 영향을 주지 않는다

'Java' 카테고리의 다른 글

Java, String(2)  (0) 2019.10.04
Java, String(1)  (0) 2019.10.04
Java, Interger.parseInt(), 예외처리  (0) 2019.09.25
Java, Array  (0) 2019.09.25
Java, switch문  (0) 2019.09.25
switch를 이용한 학점메기기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Scanner;
public class Switch_Grading {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        char grade;
        System.out.println("점수입력: ");
        int score = sc.nextInt();
        switch(score / 10) {
            case 10:
            case 9:
                grade = 'A';
                break;
            case 8:
                grade = 'B';
                break;
            case 7:
                grade = 'C';
                break;
            case 6:
                grade = 'D';
                break;
            default:
                grade = 'F';    
        }
        System.out.println("학점은 " + grade);
        sc.close();
    }
}
 
cs

 

'Java' 카테고리의 다른 글

Java, String(2)  (0) 2019.10.04
Java, String(1)  (0) 2019.10.04
Java, Interger.parseInt(), 예외처리  (0) 2019.09.25
Java, Array  (0) 2019.09.25
Java, for-while, continue, Scanner  (0) 2019.09.25

+ Recent posts