为了账号安全,请及时绑定邮箱和手机立即绑定

BeautifulSoup 试图获取选定的值来抓取 IMDB 但出现错误

BeautifulSoup 试图获取选定的值来抓取 IMDB 但出现错误

慕的地10843 2023-05-23 10:36:03
我正在尝试使用 BeautifulSoup 从以下 HTML 中获取选定的值,但无法获取。<select id="bySeason" tconst="tt0944947" class="current">  <!--  This ensures that we don't wind up accidentally marking two options  (Unknown and the blank one) as selected.  -->  <option value="1">    1  </option>  <!--  This ensures that we don't wind up accidentally marking two options  (Unknown and the blank one) as selected.  -->  <option selected="selected" value="8">    2  </option></select>这就是我正在尝试但徒劳的。season_container = page_html.find_all("select", class_="current")print(season_container.find_all('option', selected=True))
查看完整描述

2 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

您可以通过选择使用来缩小搜索范围id。



from bs4 import BeautifulSoup


html = """<select id="bySeason" tconst="tt0944947" class="current">

  <!--

  This ensures that we don't wind up accidentally marking two options

  (Unknown and the blank one) as selected.

  -->

  <option value="1">

    1

  </option>

  <!--

  This ensures that we don't wind up accidentally marking two options

  (Unknown and the blank one) as selected.

  -->

  <option selected="selected" value="8">

    2

  </option>

</select>

"""


soup = BeautifulSoup(html, "html.parser")

selected_value = soup.find("select", {"id":"bySeason"}).find("option",selected=True)


print(selected_value.get_text(strip=True))

print("-------")

print(selected_value["value"])

输出:


2

-------

8


查看完整回答
反对 回复 2023-05-23
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

你很亲密。


season_container = page_html.find_all("select", class_="current")[0] # <- first ele. 

print(season_container.find_all('option', selected=True))

第一行返回一个数组,因此您必须指定选择(大概)第一个元素。代码的另一部分很好。


查看完整回答
反对 回复 2023-05-23
  • 2 回答
  • 0 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信