2010-02-08 91 views
7

我以這種形式需要從表中的數據在文本文件(output.txt中): 數據1,數據2,數據3,數據4; .....解析表BeautifulSoup和文本文件寫

Celkova podlahova plocha bytu;33米; Vytah;肛; Nadzemne podlazie; Prizemne podlazie; ......;備考vlastnictva; Osobne

所有 「一行」,分隔符爲 「;」(後來在csv-出口文件)。

我是初學者。幫助,謝謝。

from BeautifulSoup import BeautifulSoup 
import urllib2 
import codecs 

response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever') 
html = response.read() 
soup = BeautifulSoup(html) 

tabulka = soup.find("table", {"class" : "detail-char"}) 

for row in tabulka.findAll('tr'): 
    col = row.findAll('td') 
    prvy = col[0].string.strip() 
    druhy = col[1].string.strip() 
    record = ([prvy], [druhy]) 

fl = codecs.open('output.txt', 'wb', 'utf8') 
for rec in record: 
    line = '' 
    for val in rec: 
     line += val + u';' 
    fl.write(line + u'\r\n') 
fl.close() 

回答

11

你們不守,你在閱讀每一條記錄在records試試這個,它存儲的記錄:

from BeautifulSoup import BeautifulSoup 
import urllib2 
import codecs 

response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever') 
html = response.read() 
soup = BeautifulSoup(html) 

tabulka = soup.find("table", {"class" : "detail-char"}) 

records = [] # store all of the records in this list 
for row in tabulka.findAll('tr'): 
    col = row.findAll('td') 
    prvy = col[0].string.strip() 
    druhy = col[1].string.strip() 
    record = '%s;%s' % (prvy, druhy) # store the record with a ';' between prvy and druhy 
    records.append(record) 

fl = codecs.open('output.txt', 'wb', 'utf8') 
line = ';'.join(records) 
fl.write(line + u'\r\n') 
fl.close() 

這可能是更多的清理,但我認爲這是你是什麼缺憾。

0

這裏是一個可選的非BS方式,只爲你的任務

store=[] #to store your results 
url="""http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever""" 
page=urllib2.urlopen(url) 
data=page.read() 
for table in data.split("</table>"): 
    if "<table" in table and 'class="detail-char' in table: 
     for item in table.split("</td>"): 
       if "<td" in item: 
        store.append(item.split(">")[-1].strip()) 
print ','.join(store) 

輸出

$ ./python.py 
Celková podlahová plocha bytu,33 m2,Výťah,Áno,Nadzemné podlažie,Prízemné podlažie,Stav,Čiastočná rekonštrukcia,Konštrukcia bytu,tehlová,Forma vlastníctva,osobné 
+0

應該是 ';'。因爲在項目之間需要分號連接(店)。 – pwdyson 2010-02-09 09:44:03

+0

哇,這太好了 - 但你有一個限制,只抓住第一個項目。如何繼續獲取表中的所有數據,包括嵌套表? – itsricky 2013-01-29 23:04:06