requests.get(url).status_code
ok : 200
too many requests : 429
404 : not found
502 : Bad gateway
csv 파일 열기 pd.read_csv
import pandas as pd
pd.read_csv("./testFile.csv", index_col=0)
# index_col=0 -> Unnamed:0 컬럼 없이 csv open
csv 파일 저장
import pandas as pd
time_pd = pd.DataFrame(0., columns=col, index=time_range)
time_pd.to_csv("filename.csv")
파이썬 병렬 프로그래밍
- concurrent.future
from concurrent.futures import ThreadPoolExecutor #스레드 병렬 프로그래밍
import concurrent.futures
'''
10이라는 전체 작업(데이터)을 각 스레드에 load balancing 하고,
각 스레드는 subtask(n개로 쪼갠 데이터)에 대해 f 함수를 실행한다.
'''
def f(arr:list):
return arr
def do_thread(arr: list):
thread_list = []
all_ll=[]
with ThreadPoolExecutor(max_workers=8) as executor:
for sub_arr in arr:
thread_list.append(executor.submit(f, sub_arr)) #thread-safe function
# ...as_completed() : 스레드들이 수행한 전체 결과를 iter 객체로 만든다.
for execution in concurrent.futures.as_completed(thread_list):
all_ll+=(execution.result()) #여기서 하나의 .result()는 [0] 혹은 [1] 과 같이 [i]의 형태를 띈다
# break
return all_ll
aaa= do_thread([[i] for i in range(20)]) #[[0],[1],..,[19]]
print(aaa)
- multiprocessing
from multiprocessing import Pool #다중 프로세스 프로그래밍
import multiprocessing as mp
'''사용가능한 프로세스의 개수 출력'''
print(mp.cpu_count())
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p: #5개의 프로세스를 사용하겠다. 를 의미
print(p.map(f, [1, 2, 3]))
'''
표준 출력으로 다음과 같은 것을 인쇄합니다
[1, 4, 9]
'''
.... 멀티프로세스 + 멀티 스레드를 사용한 병렬 웹 크롤링
DataFrame 컬럼 unique() & value_counts()
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'],
'conference': ['East', 'East', 'East', 'West', 'West', 'East'],
'points': [11, 8, 10, 6, 6, 5]})
df.team.unique() # 중복을 제거한 유니크 값들을 출력
# -> ['A' 'B' 'C'] 출력
df.team.value_counts() # 컬럼 내 값들이 몇번 카운팅 되었는지를 출력
'''
A 3
B 2
C 1
Name: team, dtype: int64 를 출력
'''
list 로 감싸진 여러개의 dictionary 데이터를 dataframe 으로 변환
test_data= [{name:'djh0211', age:16}, {name:'dmh0728', age:14},{name:'bkm4040', age:25},]
test_result = pd.DataFrame.from_records(test_data)
name | age | |
0 | djh0211 | 16 |
1 | dmh0728 | 14 |
2 | bkm4040 | 25 |
생성된 데이터프레임
매번 다른 UserAgent 를 사용하여 request 보내기. user_agent
import requests
from user_agent import generate_user_agent, generate_navigator
''' pip install user_agent 필요'''
url= 'https://naver.com"
print(generate_user_agent(device_type='desktop'))
print(generate_user_agent(device_type='desktop'))
''' 매번 함수를 실행할때마다 다른 에이전트 값을 string으로 반환한다. '''
''' 매번 다른 환경으로 해당 url에 접속 '''
for i in range(5):
ua = generate_user_agent(device_type='desktop')
headers = {'User-Agent': ua}
response = requests.get(url,headers=headers)
'TIL' 카테고리의 다른 글
1월 2주차 정리 html에서 표 가져오기 | 디렉토리 내 파일 탐색 | 파일 확장자 검사 | 사용자 정의 예외처리 | 디렉토리 내 모든 데이터프레임 합치기 | 데이터프레임 정렬 및 인덱스 초기화 | 로.. (0) | 2023.01.14 |
---|---|
01.08 vi 문자열찾기 | 환경변수 추가 | 리스트간집합연산 (0) | 2023.01.08 |
01.01 datetime | pass vs continue | 예외처리 | json.dump | 파이썬 API 호출 | Thunder Client (1) | 2023.01.01 |
12.30 pow | 원형큐 | ASCII | reduce (0) | 2022.12.31 |
12.28 defaultdict | setrecursionlimit | 큰수 계산 (0) | 2022.12.28 |