Beautifulsoup get('value')

2024-09-30 20:29:27 发布

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

<ul class="mainview">
    <li>
        <input value="ABCD" class="origianl">
    </li>
</ul>

这是HTML行和

^{pr2}$

这是我用来获取“ABCD”的代码

我总是听到错误的说法

AttributeError: 'list_iterator' object has no attribute 'get'

我搜索了google和stackoverflow查询,但是任何一个wser都为我工作。。。 如何从输入元素获取值?在


Tags: 代码inputvaluehtml错误liullist
1条回答
网友
1楼 · 发布于 2024-09-30 20:29:27

children(类似于'list_iterator')意味着很多项,因此您得到的列表不是单个项。它甚至可以是带有一个项目的列表或空列表,但它仍然是一个列表。必须使用for循环来对列表中的每个项目使用get(),或者使用索引[0]来只获得第一个项目(如果列表不是空的)

但是在BeautifulSoup中,它不仅给出了tags(类Tag),而且还提供了没有.get()方法的标记(类NavigableString)之间的{}。在

这个代码

from bs4 import BeautifulSoup

html = '''
<ul class="mainview">
    <li>
        <input value="ABCD" class="origianl">
    </li>
</ul>
'''

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

mainview = soup.find(class_="mainview")

for child in mainview.children:
    print(type(child))

给予

^{pr2}$

最好使用nextfind()来查找单个元素,或者使用find_all()来获取元素列表。在

from bs4 import BeautifulSoup

html = '''
<ul class="mainview">
    <li>
        <input value="ABCD" class="origianl">
    </li>
</ul>
'''

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

mainview = soup.find(class_="mainview")

child = mainview.find(class_="origianl")

print(child.get('value'))

编辑:

children只给出第一级的子项(<li>),但没有这些子项(<input>)中的子项,因此您必须使用内部for循环来获得<input>,它位于<li>

from bs4 import BeautifulSoup
import bs4

html = '''
<ul class="mainview">
    <li>
        <input value="ABCD" class="origianl">
    </li>
</ul>
'''

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

mainview = soup.find(class_="mainview")

print(' - children  -')
for child in mainview.children:
    print('>    tag:', child.name)
    print('>   type:', type(child))
    #print('>content:', child)
    if isinstance(child, bs4.element.Tag):
        print('>  value:', child.get('value'))
        print('           - subchildren  -')
        for subchild in child.children:
            print('          >    tag:', subchild.name)
            print('          >   type:', type(subchild))
            #print('          >content:', subchild)
            if isinstance(subchild, bs4.element.Tag):
                print('          >  value:', subchild.get('value'))
            print('               -')

    print('     -')

结果:

 - children  -
>    tag: None
>   type: <class 'bs4.element.NavigableString'>
     -
>    tag: li
>   type: <class 'bs4.element.Tag'>
>  value: None
           - subchildren  -
          >    tag: None
          >   type: <class 'bs4.element.NavigableString'>
               -
          >    tag: input
          >   type: <class 'bs4.element.Tag'>
          >  value: ABCD
               -
          >    tag: None
          >   type: <class 'bs4.element.NavigableString'>
               -
     -
>    tag: None
>   type: <class 'bs4.element.NavigableString'>
     -

相关问题 更多 >