2014-08-29 54 views
-1

我試圖循環遍歷表格行並打印某些td。我可以單獨打印每個文件,但我不確定如何同時打印同一行上的兩個td。我想知道的是我在何處放置for循環和打印標籤以使其工作。Python:Beautifulsoup - 解析表格

<div id="main"> 
    <table> 
     <tbody> 
      <tr> 
       <td><span class="bold">answer</span> </td> 
       <td></td> 
       <td> 
        <option value="1|0|%" selected="selected">%</option> 
        <option value="100|0|fraction">fraction</option> 
        <option value="100|0|ratio">ratio</option> 
       </td> 
      </tr> 
     </tbody> 
    </table> 
</div> 

我試圖做到這一點是

def summary(url, i): 
html = wget(url) 
soup = BeautifulSoup(html) 
    for row in soup.findAll('div', {'id': 'main'}): 
     for ops in row.findAll('tr'): 
      for tds1 in ops.findAll('td'): 
       for opt in tds1.findAll('option', {'selected': 'selected'}): 
        return opt 
     for ops in row.findAll('tr'): 
      for tds1 in ops.findAll('td'): 
       for spans in tds1.findAll('span', {'class': 'bold'}): 
        return spans 
      print (i, opt, spans) 
+1

您正在分析的HTML和預期的輸出將有助於更正代碼 – shaktimaan 2014-08-29 00:41:03

+0

您確定在代碼中有'return opt'嗎?這意味着這個代碼從不打印任何東西。它也看起來像縮進問題:你確定以'湯'開始的行是縮進? – 2014-08-29 00:41:09

+0

另外,你是什麼意思「同時在同一行打印兩個」? – 2014-08-29 00:41:38

回答

0

想想你想在英國做什麼,然後制定出如何將其轉化爲Python的。

您想逐行閱讀,然後打印同一行上同一行中的兩列。你已經得到了大多數執行此代碼:

# Go row by row 
for ops in row.findAll('tr'): 
    # Go column by column 
    for tds1 in ops.findAll('td'): 
     # Print columns on the same line 
     print(tds1, end=' ') 
    # Make sure to end each line after the last column 
    print() 

我不知道你的所有其他代碼是,你爲什麼這樣做外循環兩次,爲什麼你要搜索對於列中的其他內容,爲什麼只要找到第一個值就會返回,等等 - 但和end = ' '是您缺少的部分:這就是您在同一行上打印多個內容的方式。

+0

我不想打印所有td標籤或td標籤中的所有數據,只是第一個td和另一個td標籤中的選項選擇。我添加了我想解析的html格式 – Marqui678 2014-08-29 01:07:58

+0

我不確定如何構建我正在嘗試執行的操作。我在運行代碼時遇到錯誤。 '/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python/Users/mike/PycharmProjects/convertHtml/tables_parse.py 文件「/Users/mike/PycharmProjects/convertHtml/tables_parse.py」,第42行 打印(tds1,結束=」「) ^ 語法錯誤:無效的語法 過程與退出代碼完成1' – Marqui678 2014-08-29 01:14:53

+0

@ Marqui678:OK,讓你在使用Python 2.7,但如果想要使用Python 3風格的'打印' - 作爲一個函數調用。你的原始代碼可以避免這種情況,儘管它增加了額外的括號和'repr',而不是'str',因爲它沒有使用任何關鍵字參數。我已經添加了'end =''',這會使其中斷。如果你想在2.7中使用3.x風格的'print',你需要在文件的頂部從__future__ import print_function'。如果你想做2.x樣式的'print'語句,去掉'print'語句中的括號,並將'end ='''改爲''後面的','。 – abarnert 2014-08-29 01:45:49