gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:58 24 4
gpt4 key购买 nike

我正在尝试解析:

<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

关于Python3 使用 BeautifulSoup 在 html 中查找属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49843116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com