如何对BeautifulSoup中soup.select返回值使用map获取表格表头
问题背景说明
BeautifulSoup的select()方法返回的是bs4.element.ResultSet自定义可迭代类型,并非Python原生列表,因此不支持直接调用map方法。
实现表头字符串数组的方案
方案1:转换为列表后使用map
注意原选择器仅选中表头行<tr>,需补充<th>选择器定位到具体表头单元格:
from bs4 import BeautifulSoup as Soup soup = Soup(html, features="html.parser") # 先将ResultSet转为原生列表,再调用map处理 headers = list(map(lambda x: x.text.strip(), list(soup.select("#StatusGrid thead tr th"))))
方案2:列表推导式(更推荐,可读性更高)
ResultSet支持直接迭代,无需额外转列表即可用列表推导式生成结果:
headers = [th.text.strip() for th in soup.select("#StatusGrid thead tr th")]
查看select返回值类型的方法
使用Python内置的type()函数即可打印返回值类型:
select_result = soup.select("#StatusGrid thead tr") print(type(select_result)) # 输出:<class 'bs4.element.ResultSet'>
内容的提问来源于stack exchange,提问作者Anders Lindén
相关产品推荐
相关产品推荐

