python BeautifulSoup get specific element

落爺英雄遲暮 提交于 2019-12-23 21:24:49

问题


if i have an html code like this

<div class="new_info_next">
     <input type="hidden" value="133" id="new_id" class="new_id">
     <input type="hidden" value="0" id="default_pe" class="default_pe">
</div>

and i want to get only 133 in input the first line i try this code using BeautifulSoup4

info = soup.find_all("div", {"class": "new_info_next"})
for inpu in info:
    for inpu1 in inpu.select('input'):
         print inpu1 .get('value')

but the output was

133
0

how to get only 133


回答1:


Since you only want the first element in the iterator, addressing it directly should work:

first = inpu.select('input')[0].get('value')
print(first)



回答2:


use soup.find()

by default it will get you the first element matching, so you could do:

info = soup.find("div", {"class": "new_info_next"})

and info.get('value') should be 133



来源:https://stackoverflow.com/questions/36187731/python-beautifulsoup-get-specific-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!