인공지능 공부/남박사의 파이썬 실전
(인프런) 파이썬 실전 네이버 검색어 크롤링 하기
앨런튜링_
2021. 5. 30. 18:56
import requests
from bs4 import BeautifulSoup
import time
def time_function(f):
def wrapper(*args, **kwargs):
start_time = time.time()
result = f(*args, **kwargs)
end_time = time.time() - start_time
print("{} {} time {}".format(f.__name__, args[1], end_time))
return result
return wrapper
@time_function
def r_fild_all(url, parser):
r = requests.get(url)
bs = BeautifulSoup(r.text, parser)
lists = bs.find_all("li", {"class":"ah_item"})
titles = []
for li in lists:
title = li.select("span.ah_k")[0].text
title.append(title)
return title
def r_select(url, parser):
r = requests.get(url)
bs = BeautifulSoup(r.text, parser)
lists = bs.find_all("li", {"class":"ah_item"})
lists = bs.select("li.ah_item") ##클래스명은 .으로 #id로 접근
titles = []
for li in lists:
title = li.select("span.ah_k").text
titles.append(title)
return titles
url = "https://www.naver,com"
r_fild_all(url, "html.parser")
r_select(url, "html.parser")
r_fild_all(url, "lxml")
r_select(url, "lxml")
# r = requests.get("https://www.naver.com")
# # bs = BeautifulSoup(r.text, "html.parser")
# bs = BeautifulSoup(r.text, "lxml.parser") ##lxml이 속도면에서 더 빠름!
# # lists = bs.find_all("li", {"class" : "ah_item"})
# # for li in lists:
# # print(li)
# # title = li.find("span", {"class" : "ah_k"}).text
# # print(title)
# ##select는 리스트 형태로 리턴한다.
# lists = bs.select("li.ah_item") ##클래스명은 .으로 #id로 접근
# for li in lists:
# title = li.select("span.ah_k").text
# print(title)