| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- urllib
- CRAWL
- 조건문
- 데이터
- 텍스트마이닝
- mysql
- for
- 기초
- Beautifulsoup
- 마이닝
- 데이터사이언티스트
- 파이썬
- 코딩교육
- 함수
- Request
- 인수
- 크롤링
- Pycharm
- Def
- Loop
- 입문
- 클린코드
- 반복문
- 텍스트
- if
- 시각화
- 파이썬3.5
- Python
- 매개변수
- 프로그래밍
- Today
- Total
IT is Smart
파이썬 requests모듈로 웹크롤링하기, web crawling using requests 본문
파이썬 requests모듈로 웹크롤링하기, web crawling using requests
달인최선 2016. 9. 10. 07:53소스부터 보도록 하겠습니다.
import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = 'https://thenewboston.com/search.php?type=0&sort=reputation&page==' + str(page)
source_code = requests.get(url, allow_redirects=False)
# just get the code, no headers or anything
plain_text = source_code.text.encode('ascii', 'replace')
# BeautifulSoup objects can be sorted through easy
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a', {'class': 'user-name'}):
href = link.get('href')
title = link.string # just the text, not the HTML
# print(href)
# print(title)
get_single_item_data(href)
page += 1
def get_single_item_data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
# if you want to gather photos from that user
for item_name in soup.findAll('img', {'class': 'img-responsive'}): # all photos of the user
photo='https://thenewboston.com'+item_name.get('src')
print(photo)
# if you want to gather links for a web crawler
for link in soup.findAll('a'):
href = link.get('href')
print(href)
trade_spider(1)
위 소스는 4 부분으로 나누어 설명하겠습니다.
import requests from bs4 import BeautifulSoup
이 부분은 requests와 BeautifulSoup4를 사용하기 위해 import하는 코드입니다.
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = 'https://thenewboston.com/search.php?type=0&sort=reputation&page==' + str(page)
source_code = requests.get(url, allow_redirects=False)
# just get the code, no headers or anything
plain_text = source_code.text.encode('ascii', 'replace')
# BeautifulSoup objects can be sorted through easy
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a', {'class': 'user-name'}):
href = link.get('href')
title = link.string # just the text, not the HTML
# print(href)
# print(title)
get_single_item_data(href)
page += 1
이 코드는 trade_spider라는 함수를 정의한 부분입니다. 이 함수의 기능은 지정한 url에 접근(html소스를 가져옴)해서 class='user-name'으로 되어 있는 a태크를 모두 찾아서 href값, 즉 링크와 링크제목을 수집하는 것입니다.
소스코드에서 접근하는 url의 실제 브라우징 모습은 아래와 같습니다.
이 화면을 크롬 브라우저의 개발자 도구를 이용해서 리스트 부분을 찾아보면 아래와 같습니다.
오른쪽에 html소스가 보이는 부분을 보면 진한 파란색으로 표시된 td태그 아래쪽에 연한 파란색으로 표시된 a태그가 보입니다. 그 태그의 class가 'user-name'으로 되어 있는 것을 확인할 수 있습니다. 소스코드가 바로 이 부분을 수집하는 것이 목적이라는 것을 알 수 있습니다.
3번째 부분은 아래와 같습니다.
def get_single_item_data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
# if you want to gather photos from that user
for item_name in soup.findAll('img', {'class': 'img-responsive'}): # all photos of the user
photo='https://thenewboston.com'+item_name.get('src')
print(photo)
# if you want to gather links for a web crawler
for link in soup.findAll('a'):
href = link.get('href')
print(href)
이 코드는 get_single_item_data라는 함수를 정의한 부분입니다. 바로 위의 함수에서 링크정보를 이 함수를 호출하면서 넘겨주는 부분이 있습니다.
get_single_item_data(href)
이 코드의 호출을 받아서 동작을 하게 되는데 class가 'img-responsive'로 정의되어 있는 img태크를 모두 찾아서 src속성값을 가져오는 부분과 다른 모든 a태그를 찾아서 href속성값을 가져오는 부분이 구현되어 있습니다.
trade_spider(1)
마지막으로 이 소스코드가 실행되도록 메인이 되는 trade_spider함수를 호출하는 부분입니다.
이 소스는 결국 하나의 url에 포함되어 있는 많은 링크 정보를 수집하고, 수집한 링크별로 다시 접근해서 해당 url에 포함된 모든 이미지 정보와 링크 정보를 수집하는 기능으로 구현되어 있습니다.
웹크롤링의 표준적인 구현 사례라고 할 수 있겠습니다.
소스코드를 잘 이해해서 필요한 부분을 수정하는 것만으로도 그럴 듯한 자신만의 크롤러를 구현할 수 있을 것입니다.
여기까지 입니다~
'Programming > Python Basic' 카테고리의 다른 글
| 파이썬 Class 구현하기, define and use class (0) | 2016.09.10 |
|---|---|
| 파이썬 try-except문으로 에러 처리하기, Python handles error using try-except (0) | 2016.09.10 |
| 파이썬 requests모듈 사용하기, use requests module (0) | 2016.09.09 |
| 파이썬으로 인터넷의 주가정보 수집하기, get stock information from Internet (3) | 2016.09.09 |
| 파이썬으로 txt파일 만들고 읽기, write & read txt file (0) | 2016.09.09 |