Skip to main content
 首页 » 编程设计

Python3 使用 BeautifulSoup 在 html 中查找属性值

2025年01月19日7kenshinobiy

我正在尝试解析:

<form id="main"> 
    <select {disable} id="TRANSPORT" style="font-size: 8pt;margin:0;width:250px;"> 
        <option selected value="TCP"> 
            TCP(selected) 
        </option> 
        <option value="UDP"> 
            UDP 
        </option> 
    </select> 
</form> 

TRANSPORT 的选定值。我不知道该怎么做。我尝试了什么:

from bs4 import BeautifulSoup 
f = '''<form id="main">\n 
<select {disable} id="TRANSPORT"  style="font-size:  
8pt;margin:0;width:250px;"><option selected value="TCP">TCP(selected)  
</option><option value="UDP">UDP</option></select> 
</form>>''' 
soup = BeautifulSoup(f, "lxml") 
last_tag = soup.find("select",id ="TRANSPORT") 
TRANSPORT_ID = last_tag.get('id') 
TRANSPORT_VAL = last_tag.get('selected value') 
print(TRANSPORT_ID, TRANSPORT_VAL) 

我得到结果:

TRANSPORT None 

但我必须得到结果:

TRANSPORT TCP 

因为 - TCP(已选择)

请您参考如下方法:

selected value不是 <option> 的属性标签。它只是显示当前属性 selected没有值(但属性存在),您要查找的属性是 value="TCP" .

或者,为了更好地解释,selected value="TCP"与selected="" value="TCP"相同.

所以,如果你想找到 <option>选中的标签,可以使用find('option', selected=True)并使用 get('value') 获取值.

f = ''' 
<form id="main"> 
    <select {disable} id="TRANSPORT" style="font-size: 8pt;margin:0;width:250px;"> 
        <option selected value="TCP"> 
            TCP(selected) 
        </option> 
        <option value="UDP"> 
            UDP 
        </option> 
    </select> 
</form>''' 
soup = BeautifulSoup(f, "lxml") 
 
transport = soup.find('select', id='TRANSPORT') 
transport_id = transport['id'] 
transport_value = transport.find('option', selected=True)['value'] 
print(transport_id, transport_value) 
# TRANSPORT TCP