urllib

urllib 사용법


urllib.request.urlretrieve()


import urllib.request

url = 'https://t1.daumcdn.net/daumtop_chanel/op/20200723055344399.png'
img_name = 'daumlogo.png'
urllib.request.urlretrieve(url, img_name)
print('download ok!!')

기본 사용법


import urllib.request
import urllib.parse

url = 'https://search.shopping.naver.com/book/search'
values = {'query':'파이썬'}
params = urllib.parse.urlencode(values) # 한글 처리
url += ('?' + params)
print(url)

response = urllib.request.urlopen(url)
if response.getcode() == 200:
    data = response.read()

text = data.decode('utf-8')    

모바일 페이지로 요청하기


import urllib.request

url = 'http://www.naver.com'
#url = 'http://www.daum.net'
headers = {
    'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36'
}
request = urllib.request.Request(url, headers=headers) # 요청 헤더 추가
response = urllib.request.urlopen(request)

if response.getcode() == 200:
    print(response.geturl()) # 응답 주소
    #print(response.info()) # 응답 헤더 정보