使用BeautifulSoup提取属性值

216 投票
10 回答
447441 浏览
提问于 2025-04-15 21:27

我想从网页上的一个特定的“input”标签中提取单个“value”属性的内容。我使用了以下代码:

import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()

from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)

inputTag = soup.findAll(attrs={"name" : "stainfo"})

output = inputTag['value']

print str(output)

但是我遇到了一个错误:TypeError: list indices must be integers, not str

虽然根据Beautifulsoup的文档,我知道字符串在这里应该没问题……但我不是专家,可能理解错了。

任何建议都非常感谢!

10 个回答

23

对我来说:

<input id="color" value="Blue"/>

可以通过下面的代码获取。

page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(colorName['value'])
53

Python 3.x 中,你只需要在通过 find_all 获取到的标签对象上使用 get(attr_name) 方法就可以了:

xmlData = None

with open('conf//test1.xml', 'r') as xmlFile:
    xmlData = xmlFile.read()

xmlDecoded = xmlData

xmlSoup = BeautifulSoup(xmlData, 'html.parser')

repElemList = xmlSoup.find_all('repeatingelement')

for repElem in repElemList:
    print("Processing repElem...")
    repElemID = repElem.get('id')
    repElemName = repElem.get('name')

    print("Attribute id = %s" % repElemID)
    print("Attribute name = %s" % repElemName)

这个操作是针对一个 XML 文件 conf//test1.xml,这个文件的内容大概是这样的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <singleElement>
        <subElementX>XYZ</subElementX>
    </singleElement>
    <repeatingElement id="11" name="Joe"/>
    <repeatingElement id="12" name="Mary"/>
</root>

执行后会输出:

Processing repElem...
Attribute id = 11
Attribute name = Joe
Processing repElem...
Attribute id = 12
Attribute name = Mary
268

.find_all() 方法会返回一个包含所有找到的元素的列表,所以:

input_tag = soup.find_all(attrs={"name" : "stainfo"})

input_tag 是一个列表(可能只包含一个元素)。根据你具体想要的结果,你可以选择:

output = input_tag[0]['value']

或者使用 .find() 方法,它只会返回找到的第一个元素:

input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']

撰写回答