2017-04-19 15 views
0

我正在使用beautifulsoup处理数据。get_text()返回空值。我想将它转换为无

现在我遇到了问题。

我的代码是下面

elif '임차인' and '점유부분' in table.get_text(): #임차인 현황 
    print(table) 
    for renters in table.findAll('tr')[1::]: 
     # print(renters) 
     for renter_values in renters.findAll('td', ({'class':'center'})): 
      print("It is \n" + renter_values.get_text()) 
      registration_of_businessman = renters.findAll('td', ({'class': 'left'}))[0] 
      etc = renters.findAll('td', ({'class': 'left'}))[1] 
      rental_fee = renters.find('td', ({'class': 'money'})) 

enter image description here

以上是对局部输出。您可以看到空值低于第四个'这是'

您可以在此处获取表格源。 http://blog.naver.com/khm2963/220987221959

我该如何解决这个问题?

+2

如果你想转换成'None'一个空字符串,你可以使用'(renter_values.get_text()或无)'。 – khelwood

+0

你的表达方式中的''임차인'和'部分是多余的。它可以在不改变表达式意义的情况下被移除。如果你想测试两个字符串是否存在,你需要使用不同的表达式。 –

+0

感谢您的回答。我在代码中添加'或None',如renter_values.get_text()。strip()或None。 但它返回空字符串。为什么?我该如何解决它? –

回答

2

我不确定你真正想要什么。你希望无或字符串转换为字符串'无'?这里有一个例子:

elif '임차인' and '점유부분' in table.get_text(): #임차인 현황 
    print(table) 
    for renters in table.findAll('tr')[1::]: 
     # print(renters) 
     for renter_values in renters.findAll('td', ({'class':'center'})): 
      return_value = renter_values.get_text() 
      if return_value: 
       print("It is \n" + return_value) 
      registration_of_businessman = renters.findAll('td', ({'class': 'left'}))[0] 
      etc = renters.findAll('td', ({'class': 'left'}))[1] 
      rental_fee = renters.find('td', ({'class': 'money'})) 

在考察beautifulSoup get_text方法我发现这个方法将返回一个'',如果有哪里用这种方法没有catched_values。它在字符串分隔符上使用.join()函数。这样该方法返回一个空字符串是正确的。如果您确实需要None作业,请在return_value作业下添加一行,如:return_value = return_value if len(return_value) > 0 else None

在下面的代码:

def get_text(self, separator=u"", strip=False, types=(NavigableString, CData)): 
    """ 
    Get all child strings, concatenated using the given separator. 
    """ 
    return separator.join([s for s in self._all_strings(
       strip, types=types)]) 
+0

我想将空字符串转换为无。感谢您的回答。上面不起作用 –

+0

没问题:)你的意思是我的代码不工作(因为它在上面)或者其他答案不起作用? –

+0

在python中''None''会给你一个条件中的'False''声明。空字符串如''''''也会给你一个'False''声明。如果你真的需要''None'',你可以在return_value赋值下面添加一行:''return_value = return_value if len(return_value)> 0 else None'' –

0

空值出现,因为该空间在叶标签找到。

你必须要对“白色空间只字符串”过滤器,如下

for renter_values in renters.findAll('td', ({'class':'center'})): 
    if renter_values.get_text().strip(): 
     print("It is \n" + renter_values.get_text()) 
+0

谢谢你的回答。但它没有奏效 –

相关问题