2013-09-02 2 views
0

4 가지 주식에 대해 웹 스크랩 PE 비율을 테스트하려고합니다. 내가 잘못 가고 있는지 정확히 알지 못해서, 당신의 도움에 감사드립니다.웹 스크래핑 PE 비율

제 생각에는 욕심 많고 탐욕스러운 한정자와 어떻게 정규 표현식 URL이 복사되는지 생각해보십시오.

import urllib 
import re 

symbolslist = ["aapl","spy","goog","nflx"] 

i=0 
while i<len(symbolslist): 
    url = "http://finance.yahoo.com/q?s=" +symbolslist[i] +"&q1=1" 
    htmlfile = urllib.urlopen(url) 
    htmltext = htmlfile.read() 
    regex = '<th scope="row" width="48%">"P/E "<span class="small">(ttm)</span>: </th><td class="yfnc_tabledata1">(.+?)</td>' 
    pattern = re.compile(regex) 
    price_to_earnings = re.findall(pattern,htmltext) 
    print "The price to earnings of", symbolslist[i]," is", price_to_earnings 
    i+=1 
+2

사용합니다. 대신 HTML 구문 분석기를 사용하십시오 : –

+2

원시 입력 데이터를 보지 않고 무엇이 잘못되었는지 알 수 없습니다. 당신은 무엇을 기대하며 무엇을 기대합니까? –

+0

나는 Apple의 P/E를 12.15, S & P 500의 PE는 15, PE의 Google은 24.5, Netflix의 PE는 353이 될 것으로 예상한다. 좋은 html 파서? 도와 주셔서 감사합니다. –

답변

0

이 솔루션은 문제는 당신이 HTML을 구문 분석 정규식 등에서 특정 요소를 뽑아 오기를 사용하려는 것입니다 BeautifulSoup

import re 
import urllib 

try: 
    #Using bs4 
    from bs4 import BeautifulSoup 
    from bs4 import Tag 
except ImportError: 
    #Using bs3 
    from BeautifulSoup import BeautifulSoup 
    from BeautifulSoup import Tag 

def check_th(iarg): 
    if(iarg.name == u"th" and bool(set([(u"scope", u"row")]) <= set(iarg.attrs))): 
     if(any([bool(re.search("\s*P/E\s*", str(x))) for x in iarg.contents])): 
      return True 
    return False 

tag_locations = \ 
[ 
    lambda x: x.name == u"table" and bool(set([(u"id", u"table2")]) <= set(x.attrs)), 
    lambda x: x.name == u"tr", 
    check_th 
] 

symbolslist = ["aapl","spy","goog","nflx"] 

for symbol in symbolslist: 
    url = "http://finance.yahoo.com/q?s=" + symbol +"&q1=1" 
    htmlfile = urllib.urlopen(url) 
    htmltext = htmlfile.read() 
    soup = BeautifulSoup(htmltext) 
    found_tags = [soup] 
    for tag_location in tag_locations: 
     if(found_tags): 
      found_tags = [x for found_tag in found_tags for x in found_tag.findAll(tag_location)] 

    if(found_tags): 
     data_tag = found_tags[0].findNextSibling(lambda x: x.name == u"td" and bool(set([(u"class", u"yfnc_tabledata1")]) <= set(x.attrs))) 

     print "The price to earnings of %(company)s is %(ratio)s" % {"company" : symbol, "ratio" : data_tag.text}