BeautifulSoup ...不一致字段(可能存在或可能不存在)

时间:2018-06-26 13:34:36

标签: python python-3.x web-scraping beautifulsoup

field_b可能存在或可能不存在。 print(field_b.text)导致

AttributeError: 'NoneType' object has no attribute 'text'

代码:

soup=BeautifulSoup(result, 'lxml')

for item in soup.find_all('li', class_='items'):
    field_a=item.find('span', class_='aaa')
    field_b=item.find('span', class_='bbb')
    field_c=item.find('span', class_='ccc')

    print(field_a.text,field_b.text,field_c.text)



result
------
<li class="items><span class="aaa">XXX</span><span class="bbb">XXX</span><span class="ccc">XXX</span></li>
<li class="items><span class="aaa">XXX</span><span class="ccc">XXX</span></li>
<li class="items><span class="aaa">XXX</span><span class="ccc">XXX</span></li>
<li class="items><span class="aaa">XXX</span><span class="bbb">XXX</span><span class="ccc">XXX</span></li>

0 个答案:

没有答案