URL 관련한 작업을 하고 있다면, 원하는 부분만 추출하고 싶을 때가 있다. 아래의 예시를 살펴보자.
https://docs.python.org/3.5/search.html?q=urllib&check_keywords=yes
요녀석은 대략 4가지 부분으로 이루어져 있는데,
scheme
netloc
path
query
라고 부분별 명칭이 있다.
이걸 re 를 써서 정규식으로 추출하려고 하면 머리가 아파질텐데, 다행히 built-in 라이브러리 중에 이걸 자동으로 해주는 녀석이 있다.
re
from urllib.parse import urlparse url = 'https://docs.python.org/3.5/search.html?q=urllib&check_keywords=yes' urlparse(url) # ParseResult(scheme='https', netloc='docs.python.org', path='/3.5/search.html', params='', query='q=urllib&check_keywords=yes', fragment='')
정규식으로 Url을 파싱하려고 하고 있다면 꼭 urllib을 먼저 써보도록 하자.
아래는 여러 Url들에 대한 예시:
랜덤 url 출처: https://www.randomlists.com/urls?qty=10
from urllib.parse import urlparse import pandas as pd urls = ['https://docs.python.org/3.5/search.html?q=urllib&check_keywords=yes&area=default', 'http://www.example.org/achiever?boundary=arm&activity=bike#attack', 'https://example.org/', 'https://www.example.com/?airport=birds', 'https://www.example.com/', 'http://www.example.com/?books=adjustment&activity=army', 'http://www.example.com/beef/advertisement', 'https://www.example.com/box.aspx?actor=advertisement', 'https://example.com/battle.php', 'http://example.com/#bone', 'https://example.com/?ball=believe#aftermath'] print(pd.DataFrame([urlparse(u) for u in urls])) scheme netloc path params \ 0 https docs.python.org /3.5/search.html 1 http www.example.org /achiever 2 https example.org / 3 https www.example.com / 4 https www.example.com / 5 http www.example.com / 6 http www.example.com /beef/advertisement 7 https www.example.com /box.aspx 8 https example.com /battle.php 9 http example.com / 10 https example.com / query fragment 0 q=urllib&check_keywords=yes&area=default 1 boundary=arm&activity=bike attack 2 3 airport=birds 4 5 books=adjustment&activity=army 6 7 actor=advertisement 8 9 bone 10 ball=believe aftermath
[python] URL에서 원하는 부분만 예쁘게 추출하기 - urllib
URL 관련한 작업을 하고 있다면, 원하는 부분만 추출하고 싶을 때가 있다. 아래의 예시를 살펴보자.
요녀석은 대략 4가지 부분으로 이루어져 있는데,
scheme
: httpsnetloc
: docs.python.orgpath
: /3.5/search.htmlquery
: q=urllib&check_keywords=yes라고 부분별 명칭이 있다.
이걸
re
를 써서 정규식으로 추출하려고 하면 머리가 아파질텐데, 다행히 built-in 라이브러리 중에 이걸 자동으로 해주는 녀석이 있다.정규식으로 Url을 파싱하려고 하고 있다면 꼭 urllib을 먼저 써보도록 하자.
아래는 여러 Url들에 대한 예시:
랜덤 url 출처: https://www.randomlists.com/urls?qty=10
'Python' 카테고리의 다른 글