오늘 한 것
✅ 권자경 튜터님과 상담
✅ 데이터 분석- chap.2 파이썬을 이용한 웹 스크래핑 강의 듣기
^ 라인의 처음을 매칭
$ 라인의 끝을 매칭
. 임의의 문자를 매칭 (와일드 카드)
\s 공백 문자를 매칭
\S 공백이 아닌 문자를 매칭
* 바로 앞선 문자에 적용되고 0 혹은 그 이상의 앞선 문자와 매칭을 표기함.
*? 바로 앞선 문자에 적용되고 0 혹은 그 이상의 앞선 문자와 매칭을 탐욕적이지 않은 방식으로 표기함.
+ 바로 앞선 문자에 적용되고 1 혹은 그 이상의 앞선 문자와 매칭을 표기함
+? 바로 앞선 문자에 적용되고 1 혹은 그 이상의 앞선 문자와 매칭을 탐욕적이지 않은 방식으로 표기함.
[aeiou] 명세된 집합 문자에 존재하는 단일 문자와 매칭. “a”, “e”, “i”, “o”, “u” 문자만 매칭되는 예제
[a-z0-9] - 기호로 문자 범위를 명세할 수 있다. 소문자이거나 숫자인 단일 문자만 매칭되는 예제.
( ) 괄호가 정규표현식에 추가될 때, 매칭을 무시한다. 하지만 findall()을 사용 할 때 전체 문자열보다 매칭된 문자열의 상세한 부속 문자열을 추출할 수 있게 한다.
만약 다음 문장에서 '^F.+:'라는 패턴과 일치하는 부분을 찾는다면,
x = 'From: Using the : character'
From: <- X
From: Using the : <- O
이라는 두 가지 부분이 모두 패턴과 일치. 일치하는 여러 패턴이 있을 경우 가장 긴 것을 선택.
import re
x = 'From: Using the : character'
y = re.findall('^F.+?:', x)
print(y)
# ['From:']
x = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
y = re.findall('^From (\S+@\S+)',x)
print(y)
# ['stephen.marquard@uct.ac.za']
[ ] 안의 ^는 not이라는 뜻
[^ ] -> 공백이 아닌
import re
lin = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
y = re.findall('^From .*@([^ ]*)',lin)
print(y)
# ['uct.ac.za']
import re
hand = open('mbox-short.txt')
numlist = list()
for line in hand:
line = line.rstrip()
stuff = re.findall('^X-DSPAM-Confidence: ([0-9.]+)', line)
if len(stuff) != 1 : continue
num = float(stuff[0])
numlist.append(num)
print('Maximum:', max(numlist))
import re
x = 'We just received $10.00 for cookies.'
y = re.findall('\$[0-9.]+',x)
print(y)
# ['$10.00']
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect( ('data.pr4e.org', 80) )
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode(),end='')
mysock.close()
import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('http://www.dr-chuck.com/page1.html')
for line in fhand:
print(line.decode().strip())
※ 요새는 requests 라이브러리로 더 간단하게 함.
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
url = input('Enter - ')
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print(tag.get('href', None))
※ 요새는 정적 페이지보다 동적 페이지가 많기 때문에 Selenium나 Playwright를 추가로 사용