用beautifulsoup提取属性值

2024-09-27 07:19:17 发布

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

我试图提取网页上特定“输入”标记中单个“值”属性的内容。我使用以下代码:

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:列表索引必须是整数,而不是str

尽管从Beautifulsoup文档中我了解到字符串在这里不应该是一个问题。。。但我不是专家,我可能误解了。

任何建议都非常感谢! 提前谢谢。


Tags: 代码标记importhttp网页内容readoutput
3条回答

如果要从上面的源检索属性的多个值,可以使用findAll和列表理解来获取所需的所有内容:

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

from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)

inputTags = soup.findAll(attrs={"name" : "stainfo"})
### You may be able to do findAll("input", attrs={"name" : "stainfo"})

output = [x["stainfo"] for x in inputTags]

print output
### This will print a list of the values.

.findAll()返回所有找到的元素的列表,因此:

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

inputTag是一个列表(可能只包含一个元素)。根据您的具体要求,您应该:

 output = inputTag[0]['value']

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

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

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

相关问题 更多 >

    热门问题