2016-03-02 51 views
1

我试图从使用BeautifulSoup的HTML源提取数据。这是源如何处理其colspan ==''的td标签?

<td class="advisor" colspan=""> 

这里是我的代码:

soup = BeautifulSoup(html, 'html.parser') 
tds = soup.find_all('td') 

for td in tds: 
    if td["colspan"] == '': 
     col = 0 
    else: 
     col = int(td["colspan"]) 

不过,我得到这个错误:

ValueError: invalid literal for int() with base 10: '' 

我知道这个错误意味着'不能转化为整数,但为什么我的'如果'不工作?我认为这种情况应该去

col = 0 

而不是

col = int(td["colspan"]) 
+0

你可以做'如果td [“colspan”]。strip()=='':'看看是否有帮助吗? – shahkalpesh

+0

可以包括'A,B,C,D,E,F'吗? – Ian

+0

@shahkalpesh它不起作用。你能告诉我什么是strip()吗?我以前在文档中没有看到它。谢谢:) –

回答

2

我会建议你使用异常处理如下:

from bs4 import BeautifulSoup 

html = """ 
    <td class="advisor" colspan="2"></td> 
    <td class="advisor" colspan=""></td> 
    <td class="advisor" colspan="x"></td> 
    """ 

soup = BeautifulSoup(html, 'html.parser') 
tds = soup.find_all('td') 

for td in tds: 
    try: 
     col = int(td["colspan"]) 
    except (ValueError, KeyError) as e: 
     col = 0 

    print(col) 

这将显示如下:

2 
0 
0 

使用Python 3.4.3

+0

我试过了你的代码,但是它仍然给我ValueError ... –

+0

我试过上面的脚本,网址,它似乎工作正常。它产生很多0,有几个2。你使用的是什么版本的Python和BeautifulSoup? –

+0

我也收到了所有的colspan值,结果与你的一样。它真的很奇怪,如果没有工作... 我的python版本是3.5.1和BS4 –

1

为了避免错误,由于错误输入类型,你可以检查的说法是真的完整的第一,然后再继续:

def check_int(s): 
    if s = '' or s is None 
     return False 
    st = str(s) 
    if st[0] in ('-', '+'): 
     return st[1:].isdigit() 
    return st.isdigit() 

for td in tds: 
    if check_int(td["colspan"]): 
     col = int(td["colspan"]) 
    else: 
     col = 0 

或者,使用三元操作:

for td in tds: 
    col = int(td["colspan"]) if check_int(td["colspan"]) else 0 

编辑:一些good materials做int检查没有尝试除外。

+0

谢谢你的帮助!我终于发现这是我的错!我知道为什么它不工作!谢谢:) –

+0

@MarsLee ow,这对你很有好处..;) – Ian

0

测试你可以假设值var col的全称是"",然后检查它是否属实。

soup = BeautifulSoup(html, 'html.parser') 
tds = soup.find_all('td') 

for td in tds: 
    col = 0 
    if td["colspan"].isdigit(): 
     col = int(td["colspan"]) 
+0

你的策略很酷,但我仍然得到ValueError。我不知道为什么... –

+0

试着把一些打印值调试一下。 –

+0

我打印所有的colspan值,我非常确定它是'',所以'if'不起作用真的很奇怪。 –