2011-04-29 3 views
1

나는 다음과 같은 BeautifulSoup로 스크립트를 사용하여 처음 30 개 TED 동영상 (비디오의 이름과 URL)을 찾기 위해 노력하고 있지만 :아름다운 수프와 문

import urllib2 
from BeautifulSoup import BeautifulSoup 

total_pages = 3 
page_count = 1 
count = 1 

url = 'http://www.ted.com/talks?page=' 

while page_count < total_pages: 

    page = urllib2.urlopen("%s%d") %(url, page_count) 

    soup = BeautifulSoup(page) 

    link = soup.findAll(lambda tag: tag.name == 'a' and tag.findParent('dt', 'thumbnail')) 

    outfile = open("test.html", "w") 

    print >> outfile, """<head> 
      <head> 
        <title>TED Talks Index</title> 
      </head> 

      <body> 

      <br><br><center> 

      <table cellpadding=15 cellspacing=0 style='border:1px solid #000;'>""" 

    print >> outfile, "<tr><th style='border-bottom:2px solid #E16543; border-right:1px solid #000;'><b>###</b></th><th style='border-bottom:2px solid #E16543; border-right:1px solid #000;'>Name</th><th style='border-bottom:2px solid #E16543;'>URL</th></tr>" 

    ted_link = 'http://www.ted.com/' 

    for anchor in link: 
      print >> outfile, "<tr style='border-bottom:1px solid #000;'><td style='border-right:1px solid #000;'>%s</td><td style='border-right:1px solid #000;'>%s</td><td>http://www.ted.com%s</td></tr>" % (count, anchor['title'], anchor['href']) 

    count = count + 1 

    print >> outfile, """</table> 
        </body> 
        </html>""" 

    page_count = page_count + 1 

코드는 괜찮아 보이는 마이너스 두 가지 :

  1. 카운트가 증가하지 않는 것 같습니다. 그것은 단지 처음 페이지의 내용 즉, 즉 처음 30 개가 아닌 10 개의 비디오를 찾습니다. 왜?

  2. 이 코드를 사용하면 많은 오류가 발생합니다.

코드 :

total_pages = 3 
page_count = 1 
count = 1 

url = 'http://www.ted.com/talks?page=' 

while page_count < total_pages: 

page = urllib2.urlopen("%s%d") %(url, page_count) 
+0

그것은 당신의 문제가 해결되지 않습니다하지만 당신은''대신''와''태그의 태그 두 개의 구멍이 있습니다 (IE'인쇄 >> OUTFILE을, "" "는'해야' –

답변

1

먼저, 간단하게 루프 및 제거 I합니다 (urlopen와 나는 (논리적 여기에 원하는 "% s의 % d 개")를 구현하는 방법 밖에 모르는 이 경우 상용구 cruft에에 양 몇 가지 변수 :. 당신은 단지 10 개 개의 결과를 본 이유는 대신 각 반복을 재개의 루프의 외부에서 파일을 열 수 있도록

for pagenum in xrange(1, 4): # The 4 is annoying, write it as 3+1 if you like. 
    url = "http://www.ted.com/talks?page=%d" % pagenum 
    # do stuff with url 

그러나이입니다 회담 11-20 네가 생각한대로 처음 10 분이 아닌. 처음에는 두 페이지 만 처리 한 page_count < total_pages을 제외하고는 21-30이었습니다.) 그리고 모든 링크를 한 번에 모은 다음 나중에 출력을 작성하십시오. HTML 스타일링을 제거 했으므로 코드를 쉽게 따라 할 수 있습니다. 대신 CSS (인라인 < style> 요소)를 사용하거나 원하는 경우 다시 추가하십시오.

import urllib2 
from cgi import escape # Important! 
from BeautifulSoup import BeautifulSoup 

def is_talk_anchor(tag): 
    return tag.name == "a" and tag.findParent("dt", "thumbnail") 
links = [] 
for pagenum in xrange(1, 4): 
    soup = BeautifulSoup(urllib2.urlopen("http://www.ted.com/talks?page=%d" % pagenum)) 
    links.extend(soup.findAll(is_talk_anchor)) 

out = open("test.html", "w") 

print >>out, """<html><head><title>TED Talks Index</title></head> 
<body> 
<table> 
<tr><th>#</th><th>Name</th><th>URL</th></tr>""" 

for x, a in enumerate(links): 
    print >>out, "<tr><td>%d</td><td>%s</td><td>http://www.ted.com%s</td></tr>" % (x + 1, escape(a["title"]), escape(a["href"])) 

print >>out, "</table>" 

# Or, as an ordered list: 
print >>out, "<ol>" 
for a in links: 
    print >>out, """<li><a href="http://www.ted.com%s">%s</a></li>""" % (escape(a["href"], True), escape(a["title"])) 
print >>out, "</ol>" 

print >>out, "</body></html>" 
+0

감사합니다. "from cgi import escape"에 대해 설명해 주시겠습니까? – EGP

+0

@AdamC .: URL 또는 제목 중 하나에 HTML의 특수 문자, 즉 &, <또는 "(하나의 출력에서 ​​큰 따옴표를 사용했기 때문에) 이스케이프 (escape)가 잘못된 마크 업을 생성하지 않도록 escape()를 처리합니다 .cgi 모듈에서 다른 것을 원하지는 않지만 stdlib 이 편리한 기능을 포함하고 있습니다. http://docs.python.org/library/cgi.html#cgi.escape –