使用Beautiful Soup获取带data-bind元素数据返回NONE求助
问题分析与解决方法
你的代码返回None是因为查找条件错误:你用了{'class': 'Model.court'},但目标span的class是small,Model.court是data-bind属性的值,并非class属性内容。
正确的解析方法
可以通过以下几种方式获取目标文本:
方法一:通过data-bind属性精准定位
from bs4 import BeautifulSoup response_soup = BeautifulSoup(response.text, 'html.parser') # 匹配data-bind属性值完全匹配的span标签 court_span = response_soup.find('span', {'data-bind': 'html: model.Court'}) # 先判断元素是否存在,避免报错 if court_span: court = court_span.text.strip() else: court = "未找到Court信息" print(court)
方法二:通过相邻元素关系定位
利用目标span与前置“Court”标签的位置关联查找:
from bs4 import BeautifulSoup response_soup = BeautifulSoup(response.text, 'html.parser') # 先找到包含"Court"文本的span标签 court_label = response_soup.find('span', text='Court') if court_label: # 获取该span的父div的下一个兄弟div,再提取其中的span文本 court_div = court_label.parent.find_next_sibling('div') if court_div: court = court_div.find('span').text.strip() else: court = "未找到Court信息" print(court)
方法三:通过class属性结合筛选条件定位
如果页面中small类的span数量较少,可先批量获取再筛选:
from bs4 import BeautifulSoup response_soup = BeautifulSoup(response.text, 'html.parser') # 获取所有class为small的span标签 court_spans = response_soup.find_all('span', class_='small') for span in court_spans: # 筛选出data-bind属性符合要求的标签 if span.get('data-bind') == 'html: model.Court': court = span.text.strip() break else: court = "未找到Court信息" print(court)
注意事项
- 调用
.text前务必先判断元素是否存在,防止出现AttributeError - 使用
.strip()可去除文本前后的空白字符,让结果更整洁
内容的提问来源于stack exchange,提问作者chatmomma
相关产品推荐
相关产品推荐

