从选择中解析选项

2024-06-26 11:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图获得以下信息:

<select name="Detect" id="313" class="select" style="display: none;">
<option value="650" maxmad="15" maxpad="2" status="TRUE" context="24"> 5 </option>

<option value="660" maxmad="16" maxpad="2" status="TRUE" context="25"> 6 </option>

我想从“value”中刮出650个,从“maxmad”中刮出15个,然后像这样打印出来(有很多这样的选项,我想打印所有选项):

650: 15
660: 16
670: 17
etc
etc

以下是我尝试过的:

driver = webdriver.PhantomJS()
window = driver.set_window_size(1120, 550)
site = driver.get("www.website.com")
soup = BeautifulSoup(site, "html.parser")
for option in soup.find_all("option"):
    print('id: {}, maxmad: {}'.format(option['id'], option.text))

Tags: idtruevalue选项driverstatuscontextetc
1条回答
网友
1楼 · 发布于 2024-06-26 11:08:49

这里有多个错误,因为您每次都下载页面,所以更难找到并尝试。您应该首先创建一个包含相关代码的最小HTML文件,然后使用该文件测试解析代码

然后,您会注意到第一件事,您在应该使用soup.find_all的地方使用了site.find_all。修复后,您将发现option没有id,您应该搜索select以获得id

from bs4 import BeautifulSoup

html_str = """
<html>
<body>
<select name="Detect" id="313" class="select" style="display: none;">
<option value="650" maxmad="15" maxpad="2" status="TRUE" context="24"> 5 </option>
<option value="660" maxmad="16" maxpad="2" status="TRUE" context="25"> 6 </option>
</body>
</html>
"""

soup = BeautifulSoup(html_str, "html.parser")
select = soup.select("select")[0]
for select in soup.select("select"):
    ident = select['id']
    for option in select.find_all("option"):
        print('value: {}, maxmad: {}'.format(option['value'], option['maxmad'])

其中:

value: 650, maxmad:  15 
value: 660, maxmad:  16 

相关问题 更多 >