【问题标题】:Scrape text from selected option from dropdown从下拉列表中的选定选项中刮取文本
【发布时间】:2021-01-15 07:50:17
【问题描述】:
如何使用 python 从 HTML 结构中获取所选选项的文本?
<select class="required" id="PPT" name="PPT">
<option value="">Paying Term</option>
<option selected="selected" value="0-10">0-10 Years</option>
<option value="10-20">10-20 Years</option>
<option value="20-30">20-30 Years</option>
<option value="30-40">30-40 Years</option>
</select>
【问题讨论】:
标签:
python
selenium
web
beautifulsoup
screen-scraping
【解决方案1】:
这应该对你有帮助:
from bs4 import BeautifulSoup as soup
html_soup = soup('<select class="required" id="PPT" name="PPT"><option value="">Paying Term</option><option selected="selected" value="0-10">0-10 Years</option><option value="10-20">10-20 Years</option><option value="20-30">20-30 Years</option><option value="30-40">30-40 Years</option></select>','html.parser') #Creates a BeautifulSoup object
opt = html_soup.find_all('option',selected = "selected") #Finds all occurrences under the option tag where selected = "selected"
for x in opt:
print(x.text)
输出:
0-10 Years