2016년 12월 22일 목요일

[Python] scrapy 홈페이지 크롤링


아래의 페이지의 데이터를 가져오겠다.


















1)전체 가져오기


먼저 내가 만든 scrapy프로젝트의 item.py를 수정한다.
Field()함수를 사용해 클래스 형태의 데이터를 변수에 담는다.
scrapy.item.Field()구조로 되어 있으므로 class에 scrapy.item을 상속한다.
title, link, desc와 같이 각자 사용한 아이템을 정의한다.

















그 다음 spider에서 실행할 코드파일 (.py)를 생성하고 아래와 같이 코딩한다.
name은 고유해야 하며 실행시 구분하는 용도이다.
def parse()함수가 실제 코드가 실행되는 부분이다. 정해진 url의 데이터가 response객체에
담겨진다. 아래는 html전체를 들고와 파일에 저장하는 코드이다.




커맨트 창에서 'scrapy crawl kang(위 코드의 name)
 kang이라는 파일이 생성되었다. 확인해보면 html데이터를 전부 들고 왔다.






2)Shell

또한 대화형인 shell을 통해 실시간으로 원하는 태그 등을 확인 할 수 있다.
터미널에서 "scrapy shell 확인할url" 을 치면 ">>>" 커맨드가 나온다.

전체가 또는 부분적으로 접근할 때는 selecter를 이용해 손쉽게 사용할 수 있다.
경로는 xpath, csspath 사용할 수 있다.







위의 p태그를 우클릭으로 xpath를 복사하면 다음과 같다.
/html/body/article/section[1]/div/div[1]/div/div/p



다시 shell로 돌아가서 현재 url의 title태그 모두를 보고 싶으면
>>>response.xpath('//title')          -> 리스트 형태로 출력된다.   '//'는 모든이라는 뜻

>>>response.xpath('//title').extract()          ->데이터 형태로
>>>response.xpath('//title/text()')             ->텍스트
>>>response.xpath('//title/text()').extract()  ->텍스트만 데이터 형태로




3)부분데이터 가져오기

p태그만 출력해보자.




















[Python]리눅스에서 환경변수 설정


bash쉘의 기준으로(터미널에서 echo $SHELL 로 자신의 쉘 종류를 확인)
1. 자신의 홈 디렉토리에서 .profile파일을 연다.

2. export PATH=/usr/local/bin:$PATH
   export PYTHONPATH= ~/PATH설정할 DIR이름     
   이 문장들을 추가

3. 터미널에서 source .profile 입력하여 파일 갱신
4. python으로 들어가 
   >>>import sys
   >>>sys.path
   로 자신이 설정한 Path를 확인할 수 있다.    

2016년 12월 20일 화요일

[Algorithm] recursive을 이용 factorial

[fibonacci number]
Ex]0+1+1+2+3+5+8+13
                                   
n= 6;
fibonacci(n) =  8

public int fibonacci(int n){
 if(n<2)
return n;
 else
return f(n-1) + f(n-2);
}


최대공약수[Euclid Method]
public static int gcd(int m, int n){
if(m<n){
int tmp = n; m=n; n=tmp;
}
if(m%n==0)
return n;
else
retrun gcd(n,m%n);
}

더 간단한 버전
public static int gcd(int m, int n){
if(n==0)
return m;
else
return gcd(n,M%n);
}



-모든 반복문은 recursive로 표현할 수 있다

2016년 12월 12일 월요일

[Python] python을 통한 web crawling_Beautifulsoup VS Scrapy

Beautifulsoup
-HTML문서에서 정보를 가져올 수 있는 Navigating이 잘 되어있다.
-자동으로 UTF-8로 출력한다.
-lxml, html5lib파서를 이용한다.
-http://www.crummy.com/software/BeautifulSoup/bs4/doc

Scarpy
-web scraper framework
-다양한 selector 지원
-파이프 라인
-로깅
-이메일
-http://doc.scrapy.org/en/0.24/intro/tutorial.html


scrapy startprogect tutorial(프로젝트이름) //프로젝트 만듬
-items.py : 데이터를 들고 올때 클레스형태로 만들어 줌
-pipelines.py : 데이터 후 처리를 위한 행동들 db입력,
-setings : pipe라인 순서 등 다양한 설정들을 정함
-spiders : 스크랩할 내용들을 프로그래밍 하는 곳.

2016년 12월 9일 금요일

[Python] 문법 (feat 점프 투 파이썬)


[Python] 문자열 관련

1. 시퀀스 자료형 : 문자열, 리스트, 튜플
1) 인덱싱(indexing) : [k]
>>> s = 'abcdef' # 문자열
>>> l = [100, 200, 300] # 리스트>>> s[0] # 참조
'a'
>>> s[1]
'b'
>>> s[-1]
'f'
>>> l[1]
200
>>> l[1] = 900 # 치환
2) 슬라이싱(Slicing) : [s:t]
>>> s = 'abcdef'
>>> l = [100, 200, 300]
>>> s[1:3] # 1번 위치와 3번 위치 사이를 나타냄

'bc'
>>> s[1:] # 1부터 끝까지
'bcdef'
>>> s[:] # 처음부터 끝까지'abcdef'
>>> s[-100:100] # 범위를 넘어서면 범위 내의 값으로 자동 처리'abcdef'
>>> l[:-1] # 맨 오른쪽 값을 제외하고 모두[100, 200]
>>> s[::2] # 2칸 단위로

'ace'
>>> s[::-1] # 거꾸로
'fedcba'
3) 연결하기(Concatenation) : +
>>> s = 'abc' + 'def'
>>> s
'abcdef'

>>> L = [1, 2, 3] + [4, 5, 6]
>>> L

[1, 2, 3, 4, 5, 6]
4) 반복하기(Repetition) : *
>>> s = 'Abc'
>>> s * 4
'AbcAbcAbcAbc'

>>> L = [1, 2, 3]
>>> L * 2
[1, 2, 3, 1, 2, 3]
5) 멤버십 테스트(Membership Test) : in
>>> t = (1, 2, 3, 4, 5)
>>> 2 in t
True

>>> 10 not in t
True
>>> 'ab' in 'abcd' # 문자열인 경우 부분 문자열 확인 가능

True
6) 길이 정보 : len

>>> l = [1, 2, 3]
>>> print(len(l)) // print(len("123 123");
2. 문자열 정의
1) 한 줄 문자열 : ' or "
2) 여러 줄 문자열 : ''' or """
3) 이스케이프 문자
Escape SequenceMeaning
\newlineIgnored
\\Backslash (\)
\'Single quote (')
\"Double quote (")
\aASCII Bell (BEL)
\bASCII Backspace (BS)
\fASCII Formfeed (FF)
\nASCII Linefeed (LF)
\N{name}Character named name in the Unicode database (Unicode only)
\rASCII Carriage Return (CR)
\tASCII Horizontal Tab (TAB)
\uxxxxCharacter with 16-bit hex value xxxx (Unicode only)
\UxxxxxxxxCharacter with 32-bit hex value xxxxxxxx (Unicode only)
\vASCII Vertical Tab (VT)
\oooCharacter with octal value ooo
\xhhCharacter with hex value hh

4) 문자열 연산(시퀀스 자료형의 특징 참조)


>>> str1 = 'Firtst String'
>>> str1[0] = 'f' # 변경 불가능(Immutable) 자료형이므로 에러 발생


Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
str1[0] = 'f'
TypeError: 'str' object does not support item assignment
3. 문자열 변경
>>> s = 'spam and egg'
>>> s = s[:5] + 'cheese' + s[5:]
>>> s
'spam cheeseand egg'
4. 문자열 포매팅(Formatting) : %s, %r, %c, %d, %i, %u, %o, %x, %X, %e, %E, %f, %g, %G

>>> format = 'name = %s, age = %s'
>>> format % ('gslee', 24)
'name = gslee, age = 24'
5. 문자열 메쏘드
>>> # 대ㆍ소문자로 변환 관련 메쏘드>>> s = 'i like programming.'
>>> s.upper()
'I LIKE PROGRAMMING.'>>> s.upper().lower()
'i like programming.'
>>> 'I Like Programming'.swapcase()
'i lIKE pROGRAMMING'
>>> s.capitalize()
'I like programming.'
>>> s.title()
'I Like Programming.'
>>> # 검색 관련 메쏘드
>>> s = 'i like programming, i like swimming.'
>>> s.count('like') # 문자열 s에서 'like'라는 부분문자열이 발생한 횟수를 리턴
2
>>> s.find('like') # 'like'의 offset를 리턴(검색)
2
>>> s.find('my') # 찾는 문자열이 없을 경우 -1 리턴-1
>>> s.rfind('like') # find와 같지만 문자열 s의 뒤쪽부터 탐색22
>>> s.index('like')
2
>>> s.index('my') # find와 같지만 찾는 문자열이 없을 경우 예외 발생
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
s.index('my')
ValueError: substring not found

>>> s.rindex('like') # index와 같지만 문자열 s의 뒤쪽부터 탐색
22
>>> s.startswith('i like') # i like로 시작하는 문자열인가?
True
>>> s.endswith('swimming.') # swimming.으로 끝나는 문자열인가?True
>>> s.startswith('progr', 7) # 7번째 문자열이 progr로 시작하는가?True
>>> s.endswith('like', 0, 26) # 0부터 26번째 위치 사이의 문자열이 like로 끝나는가?True>>> # 편집 및 치환 관련 메쏘드
>>> u = ' spam and ham '
>>> u.strip() # 좌우 공백 제거
'spam and ham'
>>> u.rstrip() # 오른쪽 공백 제거
' spam and ham'
>>> u.lstrip() # 왼쪽 공백 제거
'spam and ham '
>>> ' abd '.strip()
'abd'
>>> '><>abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>> u.replace('spam', 'spam, egg') # 'spam'을 'spam, egg'로 변경
' spam, egg and ham '>>> # 문자열 분리와 결합 관련 메쏘드>>> u = ' spam and ham '
>>> u.split() # 공백으로 분리

['spam', 'and', 'ham']
>>> u.split('and') # 'and로 분리
[' spam ', ' ham ']>>> t = u.split()
>>> ':'.join(t) # ':' 문자로 결합
'spam:and:ham'
>>> print '\n'.join(t) # 줄 바꾸기로 결합
spam
and
ham

>>> lines = '''first line
second line
third line'''
>>> lines.splitlines() # 라인 단위로 분리
['first line', 'second line', 'third line']>>> s = 'one:two:three:four'
>>> s.split(':', 2) # 두 번만 분리
['one', 'two', 'three:four']
>>> s.rsplit(':', 1) # 오른쪽부터 처리['one:two:three', 'four']>>> # 정렬 관련 메쏘드>>> u = 'spam and egg'
>>> u.center(60) # 전체 60문자의 가운데에 맞춤' spam and egg '
>>> u.ljust(60) # 왼쪽에 맞춤
'spam and egg '
>>> u.rjust(60) # 오른쪽에 맞춤
' spam and egg'
>>> u.center(60, '-') # 공백 대신 '-' 문자로 채움
'------------------------spam and egg------------------------'
>>> '1\tand\t2'.expandtabs() # 탭(\t)을 8자 공백으로 사용
'1 and 2'
>>> '1\tand\t2'.expandtabs(4)
'1 and 2'>>> # 구성된 문자열의 특성 유무 파악 관련 메쏘드>>> '1234'.isdigit()
True
>>> 'abcd'.isalpha()
True
>>> '1abc234'.isalnum()
True
>>> 'abc'.islower() # 소문자인가?True
>>> 'ABC'.isupper()
True
>>> ' \t\r\n'.isspace() # 공백문자인가?True
>>> 'This Is A Title'.istitle() # 제목 문자열인가?True
>>> # 채우기 및 자리 맞추기 관련 메쏘드

>>> s = '123'
>>> s.zfill(5)
'00123'
>>> 'goofy'.zfill(6) # 빈 자리는 0으로 채워짐
'0goofy'
6.. string 모듈
>>> import string
>>> d = string.letters + string.digits
>>> d
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

>>> userid = raw_input('your id : ')
your id : creaplz510
>>> for ch in userid:
if ch not in d:
print 'invalid user id'
break
7. 유니 코드
>>> unicode('한글', 'cp949') # 인코딩을 명시적으로 알려주어야 함
u'\ud55c\uae00'
>>> unicode('한글', 'cp949').encode('utf-8') # 'utf-8' 코드로 변환
'\xed\x95\x9c\xea\xb8\x80'
>>> len('한글과 세종대왕')
15
>>> len(unicode('한글과 세종대왕', 'mbcs'))
8
>>> u = unicode('한글과 세종대왕', 'mbcs')
>>> print u[0]

>>> print u[1]

>>> ord('A') # 문자 'A'의 ASCII 코드값
65
>>> chr(65) # 코드 65에 해당하는 문자
'A'
>>> ord(unicode('가', 'cp949'))
44032
>>> hex(ord(unicode('가', 'cp949')))
'0xac00'
>>> print unichr(0xac00)

>>> print unichr(0xd7a3)

8. 문서 문자열 : 도움말 사용
# file : docstring.py
'''
Module __doc__ string
line1
line2
'''
class Ham:
"Ham class __doc__ string"
def func(self):
"Ham class func __doc__ string"
pass
>>> import docstring
>>> print docstring.__doc__
Module __doc__ string
line1
line2
>>> print docstring.Ham.__doc__
Ham class __doc__ string
>>> print docstring.Ham.func.__doc__
Ham class func __doc__ string


출처 : http://www.dreamy.pe.kr/zbxe/CodeClip/163341