如何处理其colspan ==''?的td标签

时间:2016-03-02 07:55:29

标签: python beautifulsoup

我尝试使用BeautifulSoup从html源提取数据。这是来源

<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: ''

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

col = 0

而不是

col = int(td["colspan"])

3 个答案:

答案 0 :(得分: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进行测试

答案 1 :(得分: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检查,不用try-except。

答案 2 :(得分: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"])