2017-04-14 15 views
1

我現在練習用Beautifulsoup4解析HTML。 我遇到使用find函數的問題。 這是我的代碼。在Beautifulsoup中找到函數return在第一個列表中沒有

soup1 = BeautifulSoup(a,"html.parser") 
tables1 = soup1.find('div', {'id':'auction_container'}).findAll('table') 
for table in tables1: 
if '매각기일' in table.get_text(): 
    clue1 = table.find('td', {'class': 'head_con center'}) 
    pro_clue1 = clue1.find('span', {'class':'bold'}) 
    pro_clue2 = clue1.find('span',{'class':'no'}) 
    clue2 = table.find('tr', {'valign': 'bottom'}) 
    print(clue2.find('span', {'class': 'num'})) 

變量a太長pagesource,所以我在我的博客寫了完整的腳本。你可以像這樣獲得腳本。 http://blog.naver.com/khm2963/220983094160 當我執行這個代碼,我得到了下面的輸出

None 
<span class="num"><span class="f20">2015</span>타경<span class="f20">2321</span></span> 

,當我追加的背後clue2.find('span', {'class': 'num'}).get_text()功能像print(clue2.find('span', {'class': 'num'}).get_text()),我得到了下面的錯誤。

Traceback (most recent call last): 
File "D:/python code/auction_crawl/test bs4.py", line 5895, in <module> 
print(clue2.find('span', {'class': 'num'}).get_text()) 
AttributeError: 'NoneType' object has no attribute 'get_text' 

如果我打印print(clue2).find('span', {'class': 'num'}) 我像得到下面

<tr valign="bottom"> 
<td class="head_num left"><img alt="굿옥션로고" height="26" 
src="/img/common/top_logo.gif" width="100"><span class="logo_pid"></span> 
</img> 
</td> 
<td class="head_con center"> 
<span class="bold">서울남부지방법원 본원 8계(02-2192-1338)</span>/매각기일 : 
<span class="bold"><span class="no">2017.04.12(水)</span> <span class="no"> 
(10:00)</span> 
</span></td> 
</tr> 
<tr valign="bottom"> 
<td class="head_num bold no left" style="width:190px;padding:10px 0 2px 
0;font-size:15px"><span class="num"><span class="f20">2015</span>타경<span 
class="f20">2321</span></span></td> 
<td class="head_con center" style="padding-bottom:6px"><div> 
<span class="ltblue"><img src="/img/icon/point_blue.gif" style="vertical- 
align:middle"/></span> <span class="blue bold">서울남부지방법원 본원 
</span>  <span class="ltblue"><img src="/img/icon/point_blue.gif" 
style="vertical-align:middle"/></span> 매각기일 : <span class="blue bold 
no">2017.04.12(水) (10:00)</span>  <span class="ltblue"><img 
src="/img/icon/point_blue.gif" style="vertical-align:middle"/></span> <span 
class="blue bold">경매 8계</span>(전화:02-2192-1338)</div> 
</td> 
</tr> 

所以我做了上述變量d的HTML代碼。並製作了下面的另一個代碼。

d = ''' HTML code above ''' 
soup4= BeautifulSoup(d,"html.parser") 
clue = soup4.find('span', {'class': 'num'}) 
print(clue.get_text().strip()) 

當我激活上面的代碼時,我得到了這樣的響應2015타경2321。 這就是我想要的。 我想從頂端的代碼得到2015타경2321。我怎麼才能得到它??

回答

1

您只需驗證您clue2.find('span', {'class': 'num'})有結果,如果是的話,打印出結果:

... 
clue2number = clue2.find('span', {'class': 'num'}) 
if clue2number is not None: 
    print (clue2number.get_text(strip=True)) 

,輸出:

2015年타경2321

+0

這是偉大的!真的非常感謝~~你是偉大的人類! –

相關問題