Beautiful Soup은 특히 이와 같은 빠른 작업을 위해 가장 널리 사용되는 웹 스크랩 라이브러리 중 하나입니다.
import urllib2
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://yahoo.com').read()
soup = BeautifulSoup(page)
# The page's title without html tags
soup.title.string
는 HTML 구조에 따라 달라집니다, 기사의 저자처럼, 페이지에 특정 항목을 찾기하지만 특정 CSS 태그를 찾고에 의존 전망이다 : 여기가 보일 것이다 방법
soup.find(id="author")
을
다음은 좀 더 구체적인 예입니다. 당신이 소스를 통해 보면 http://blog.sfgate.com/energy/2014/02/07/tesla-driver-blames-fatal-crash-on-new-car-smell/
, 당신은 기사 제목 클래스 blogtitle
의 <h1>
요소이며, 저자의 이름이 내부 링크입니다 것을 알 수 있습니다 :이 같은 SFGate 기사의 무리를 찾고 말 post-author
의 <span>
이다. 당신이 예에서 볼 수 있듯이
import urllib.request
from bs4 import BeautifulSoup
page = urllib.request.urlopen('http://blog.sfgate.com/energy/2014/02/07/tesla-driver-blames-fatal-crash-on-new-car-smell/').read()
soup = BeautifulSoup(page)
## Title ##
# Find the first h1 tag of class 'blogtitle'
title = soup.find("h1", "blogtitle")
# Print out just the string
print(title.string)
## Author ##
# Find the first span of class 'post-author'
author_container = soup.find("span", "post-author")
# Search inside that span for the first link
author = author_container.find("a").string
print(author)
, 당신은 각 웹 페이지의 특정 구조에 맞게 코드를 사용자 정의해야합니다, 따라서 그것은 매우 취약 할 수있다 : 즉, 다음과 같은 코드를 동일시한다. 자세한 내용은 Beautiful Soup docs을 참조하십시오.
좋은 이유가없는 한 [아름다운 수프] (http://www.crummy.com/software/BeautifulSoup/)를 사용하십시오. 이것은 일반적으로 Python에서 HTML을 파싱하는 가장 직접적인 방법으로 동의합니다. – senshin
나는 Beautiful Soup을 가지고 놀고 있었지만 협조하기 어려웠다. 나는 문서를 자세히 살펴볼 것이다 – user3285763