Python迭代中Split使用疑问:为何该函数在代码内无法调用?
问题解答
1. 为何split函数无法正常使用?
temp是列表类型,而split()是Python字符串(str)的专属方法,列表对象没有该方法。直接对列表调用split()会触发属性错误,这就是函数无法使用的原因。
2. 如何正确使用split方法?
需要遍历temp列表中的每个字符串元素,对单个字符串调用split()方法后再提取目标片段。以下是修正后的代码:
from bs4 import BeautifulSoup soup = BeautifulSoup(teste, "html.parser") Vagas = soup.find_all(title="Vaga disponível.") temp = [] for i in Vagas: on_click = i.get('onclick') temp.append(on_click) # 方式1:普通循环处理(更易读) achado2 = [] for item in temp: # 跳过空值避免索引错误 if not item: continue split_parts = item.split('\'') # 确保索引1存在再提取 if len(split_parts) >= 2: achado2.append(split_parts[1]) # 方式2:更简洁的列表推导式 achado2 = [item.split('\'')[1] for item in temp if item and len(item.split('\'')) >= 2] print(temp) print(achado2)
内容的提问来源于stack exchange,提问作者Alexandre Rodrigues
相关产品推荐
相关产品推荐

