#python 爬虫 #BeautifulSoup如何分别提取多个span标签的值

多个span标签的值提取(不含空)

如图所示,首先通过selec()或者find_all()定位到需要爬取的标签,有四个标签,然后分别提取第一,第二,第四个标签,就用列表的思路提取。然后type(star.select(‘span’)[0])为

rating_star=print(star.select('span')[0]['class'])   #评星 
rating_num=star.find_all('span')[1].text   #评分    
comments=star.find_all('span')[3].text    #评价人数

#python 爬虫 #BeautifulSoup如何分别提取多个span标签的值_第1张图片

多个span标签的值提取(含缺失标签)

但是当遇到,有的span标签缺失的情况就很尴尬,如图所示,两个span标签。但是有的第二个标签缺失。

#python 爬虫 #BeautifulSoup如何分别提取多个span标签的值_第2张图片

提取第一个标签(chi_titile)简单:
chi_title=item.select(’.title’)[0].text

但是提取第二个标签(eng_title),如果用
eng_title=item.select(’.title’)[1].text就会报错IndexError: list index out of range

参考:https://www.imooc.com/wenda/detail/506920,之后u尝试更好的方法是:
eng_title=item.find_all(‘span’,class_=‘title’)[1:2]实现第二个可能有缺失值的标签内容的提取,提取结果如下图(开心!!!!),然后type(item.find_all(‘span’,class_=‘title’)[1:2])为,同时第一个标签的提取相应为chi_title=item.find_all(‘span’,class_=‘title’)[0:1]

#python 爬虫 #BeautifulSoup如何分别提取多个span标签的值_第3张图片

小白不太懂上述操作的原理,路过的大佬可以在评论区多多指教,鞠躬₍ ᕕ⍢ᕗ⁾

你可能感兴趣的:(Py小Bug,python)