728x90
간단한 웹 크롤링
# urlopen해서 request값 가져오기
a = urllib.request.urlopen(url)
# html을 python객체로 변환
soup = BeautifulSoup(a)
# 특정 태그 찾기!
# prodList = soup.find_all(lambda tag: tag.name == 'a' and tag.get('href') and tag.text)
aList = soup.find_all("a", href=lambda href: href and "m_mall_list.php?ps_ctid=" in href)
# href 파라미터 값 가져오기
id = parse.parse_qs(parse.urlparse(prod['href']).query)['ps_ctid']
# list를 pandas DataFrame으로 생성
df = pd.DataFrame(prodList, columns = ['ct_id', 'name'])
# DataFrame to csv / csv.QUOTE_NONNUMERC은 포멧 지정 옵션
df.to_csv('ct_id.csv',index=False, encoding='utf-8-sig', quoting=csv.QUOTE_NONNUMERIC)
자바스크립트 등 웹페이지를 동적으로 가져오는 경우
브라우저를 직접 동작시키자
selenium에 webdriver를 이용할 것이다.
webdriver에 api를 통해 브라우저를 제어해서 동적 컨텐츠들도 가져올 수 있다.
selenium은 js 렌더링이 완료된 후 dom 접근이 가능하다.
from selenium import webdriver
# 크롬 웹드라이버 설정
driver = webdriver.Chrome('chromedriver')
searchUrl = url+"?ps_ctid="+ps_ctid
driver.get(searchUrl)
# 웹 로드 지연을 기다리는 최대 시간
driver.implicitly_wait(10)
# 페이지 소스 가져오기
html = driver.page_source
soup = BeautifulSoup(html)
text = soup.select_one('.goods_list_head .lnb1 .count span').text
# 태그 짜르기
percent = re.sub('<.+?>', '', percent, 0).strip()
'IT > 기록' 카테고리의 다른 글
머신러닝 02. (0) | 2020.09.15 |
---|---|
머신러닝. 01 (0) | 2020.09.15 |
고객 세분화 (0) | 2020.09.15 |
geckodriver executable needs to be in PATH. (0) | 2020.09.15 |
윈도우(Windows)에 Linux용 windows 하위 시스템(WSL) 실행 (0) | 2020.09.15 |