使用Beautiful Soup解析html表单输入标记

时间:2013-06-21 00:45:05

标签: python parsing beautifulsoup

好吧,我需要解析html表单,从“输入”,我需要提取类型为“text”的文本和任何不是文本的文本。

我有这段代码:

from BeautifulSoup import BeautifulSoup as beatsop

html_data = open("forms.html")

def html_parser(html_data)
    html_proc = beatsop(html_data)
    #We extract the text inputs.
    txtinput = html_proc.findAll('input', {'type':'text'})
    #We extract the any kind of input that is not text.
    listform = ["radio", "checkbox", "password", "file", "image", "hidden"]
    otrimput = html_proc.findAll('input', {'type':listform})

html_parser(html_data)

我将它与本地文档一起使用,但您可以使用urllib来请求任何带有表单的网页。 现在,问题是,我需要提取非文本输入表单的“value”标记,以及文本输入表单的“name”标记。 有谁知道我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:3)

要访问元素的属性,请使用element['attribute']

from BeautifulSoup import BeautifulSoup as beatsop


def html_parser(html_data):
    html_proc = beatsop(html_data)
    #We extract the text inputs.
    txtinput = html_proc.findAll('input', {'type':'text'})
    listform = ["radio", "checkbox", "password", "file", "image", "hidden"]
    otrimput = html_proc.findAll('input', {'type': listform})

    print('Text input names:')
    for elem in txtinput:
        print(elem['name'])

    print('Non-text input values:')
    for elem in otrimput:
        value = elem.get('value')
        if value:
            print(value)
        else
            print('{} has no value'.format(elem))

with open("forms.html") as html_data:
    html_parser(html_data)