
page 내에 있는 a tag의 href 속성을 모두 검색하여 출력
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon')
bsObj = BeautifulSoup(html, 'html.parser')
for link in bsObj.findAll('a'):
if 'href' in link.attrs:
print(link.attrs['href'])
이렇게 사용하면 관심 있어 하는 항목 이외의 페이지 링크가 무수히 많이 포함됨
link들은 id가 bodyContent인 div 안에 존재
URL에는 세미콜론이 포함되어 있지 않음
URL은 /wiki/로 시작됨
import re
html = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon')
bsObj = BeautifulSoup(html, 'html.parser')
for link in bsObj.find('div', {'id': 'bodyContent'}).findAll('a',
href=re.compile('^(/wiki/)((?!:).)*$)):
if 'href' in link.attrs:
print(link.attrs['href'])
함수로 표현하면,
import random
def getLinks(articleUrl):
html = urlopen('http://en.wikipedia.org' + articleUrl)
bsObj = BeautifulSoup(html, 'html.parser')
return bsObj.find('div', {'id': 'bodyContent'}).findAll('a',
href=re.compile('^(/wiki/)((?!:).)*$'))
links = getLinks('/wiki/Kevin_Bacon')
while len(links) > 0:
newArticle = links[random.randint(0, len(links) - 1)].attrs['href']
print(newArticle)
links = getLinks(newArticle)
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen('http://en.wikipedia.org' + articleUrl)
bsObj = BeautifulSoup(html, 'html.parser')
for link in bsObj.findAll('a', href=re.compile('^(/wiki/)')):
if 'href' in link.attrs:
if link.attrs['href'] not in pages:
newPage = link.attrs['href']
print(newPage)
pages.add(newPage)
getLinks(newPage)
getLinks('/wiki/Kevin_Bacon')
python에서는 재귀적으로 함수호출을 최대 1,000회까지 할 수 있다
from sys import setrecursionlimit setrecursionlimit(10**8)setrecursionlimit을 이용하면 재귀호출의 제한값을 늘릴 수 있다
- 제목은 항상 <h1> tag 안에 존재
- body 텍스트는 div#bodyContent tag 안에 존재
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen('http://en.wikipedia.org' + pageUrl)
bsObj = BeautifulSoup(html, 'html.parser')
try:
print(bsObj.h1.get_text())
print(bsObj.find(id='mw-content-text').findAll('p')[0]
except AttributeError:
print('This page is missing something!')
for link in bsObj.findAll('a', href=re.compile('^(/wiki/)')):
if 'href' in link.attrs:
if link.attrs['href'] not in pages:
newPage = link.attrs['href']
print('-' * 30 + '\n' + newPage)
pages.add(newPage)
getLinks(newPage)
getLinks('')
예외 handler에는 여러 행을 넣는 것은 위험.
1. 어떤 행에서 예외가 발생했는지 알 수 없다
2. 하나의 line에서 예외가 발생하면 뒤에 모든 line들도 실행되지 않게된다
외부링크를 이용하는 crawler를 만들기 전에는 다음에 대해 점검해야 한다