如何使用Python的BeautifulSoup获取select标签的选中选项值?
解决方法
你当前的代码在查找option时指定了{'selected':"selected"},这只会匹配带有selected="selected"属性的元素,但目标网站的selected是HTML布尔属性(无属性值),因此需要调整筛选逻辑,同时注意Python里判断空值要用None而非null。以下是两种可行的修改方案:
方案一:利用布尔属性匹配
BeautifulSoup会识别HTML布尔属性,直接使用selected=True作为筛选条件,即可匹配所有带有selected属性的option:
html = """ <select> <option value="">Please select a value</option> <option selected value = "1">Male</option> <option value = "2">Female</option> </select> """ from bs4 import BeautifulSoup soup = BeautifulSoup(html, "html.parser") dropdown = soup.find('select') # 匹配所有存在selected属性的option for option in dropdown.find_all('option', selected=True): if option is not None: print(option['value'])
方案二:使用CSS选择器
通过CSS选择器option[selected]可以更简洁地定位目标元素:
html = """ <select> <option value="">Please select a value</option> <option selected value = "1">Male</option> <option value = "2">Female</option> </select> """ from bs4 import BeautifulSoup soup = BeautifulSoup(html, "html.parser") # 直接选中带有selected属性的option selected_option = soup.select_one('select option[selected]') if selected_option: print(selected_option['value'])
内容的提问来源于stack exchange,提问作者Hamid Shah
相关产品推荐
相关产品推荐

