2012-12-26 4 views
0

다음 코드를 사용하여 URL에서 데이터를 스크랩했습니다 (코드에서 언급 됨). 코드를 실행했지만 출력이 없거나 오류가 발생하지 않았습니까? 나는 파이썬 언어가 처음이다. 어리석은 문제 일 수도있다. 누군가 나를 도울 수 있습니까?다음 코드에 대한 출력이나 오류가 발생하지 않습니까?

import csv 
import urllib2 
import sys 
import time 
from bs4 import BeautifulSoup 
page = urllib2.urlopen('http://www.t-mobile.de/smartphones/0,22727,23392-_3-0--0-all-,00.html').read() 
soup = BeautifulSoup(page) 
soup.prettify() 
with open('TMO_DE_2012-12-26.csv', 'wb') as csvfile: 
    spamwriter = csv.writer(csvfile, delimiter=',') 
    spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price"]) 
    items = soup.findAll('div', {"class": "top"},text=True) 
    prices = soup.findAll('strong', {"class": "preis-block"}) 
    for item, price in zip(items, prices): 
     textcontent = u' '.join(price.stripped_strings) 
     print unicode(item.string).encode('utf8').strip() 
     if textcontent:    
      spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") ,unicode(item.string).encode('utf8').strip(),textcontent]) 
+0

,'soup.prettify는()'이다 읽을 수있는 HTML을 출력하기위한 것이지만 출력을 사용하지는 않습니다. 사용 된대로 그 행은 아무 것도하지 않습니다. –

+0

아니요, 중복 된 계정을 만들지 않았으며, user1915050은 내 친구이고 그는 같은 프로젝트에서 저와 함께 일하고 있습니다. –

+0

오키 도키; 코딩 스타일은 다소 익숙했습니다. :-) –

답변

0

해당 페이지의 텍스트 아무 <div class="top"> 요소 이 없습니다, 그래서 items은 빈 목록입니다. text=True 필터 제거

items = soup.findAll('div', {"class": "top"}) 

을하고 그것에서 모든 텍스트 추출 :

item_text = u' '.join(item.stripped_strings) 
if textcontent and item_text:    
    spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") , item_text, textcontent]) 

또는 기존 코드에 통합 : BTW

with open('TMO_DE_2012-12-26.csv', 'wb') as csvfile: 
    spamwriter = csv.writer(csvfile, delimiter=',') 
    spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price"]) 
    items = soup.findAll('div', {"class": "top"}) 
    prices = soup.findAll('strong', {"class": "preis-block"}) 
    for item, price in zip(items, prices): 
     textcontent = u' '.join(price.stripped_strings) 
     item_text = u' '.join(item.stripped_strings) 
     if item_text and textcontent:    
      spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A"), item_text.encode('utf8'),textcontent.encode('utf8')]) 
+0

답변 해 주셔서 감사합니다. 변경 한 후에 코드를 실행했지만 "항목"이 모든 행에 대해 아무 것도 표시하지 않습니다! –

+0

@ChandanKumar : URL을 사용하여 코드를 미리 테스트했습니다. 올바른 변경을 한 것이 확실합니까? –

+0

다시 한번 감사드립니다 !! 그것은 일했다! –

관련 문제