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

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文档中,我了解到字符串在这里不应该是一个问题……但我不是专家,我可能误解了。

任何建议都非常感谢!


当前回答

我实际上会建议你一种节省时间的方法,假设你知道什么样的标签有这些属性。

假设标签xyz的属性管名为“staininfo”..

full_tag = soup.findAll("xyz")

我想让你明白full_tag是一个列表

for each_tag in full_tag:
    staininfo_attrb_value = each_tag["staininfo"]
    print staininfo_attrb_value

因此,您可以获得所有标记xyz的staininfo的所有attrb值

其他回答

如果你想从上面的源代码中检索多个属性值,你可以使用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.

我实际上会建议你一种节省时间的方法,假设你知道什么样的标签有这些属性。

假设标签xyz的属性管名为“staininfo”..

full_tag = soup.findAll("xyz")

我想让你明白full_tag是一个列表

for each_tag in full_tag:
    staininfo_attrb_value = each_tag["staininfo"]
    print staininfo_attrb_value

因此,您可以获得所有标记xyz的staininfo的所有attrb值

在Python 3中。X,简单地使用get(attr_name)在你的标签对象,你得到使用find_all:

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

我使用这个与Beautifulsoup 4.8.1来获得某些元素的所有类属性的值:

from bs4 import BeautifulSoup

html = "<td class='val1'/><td col='1'/><td class='val2' />"

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

for td in bsoup.find_all('td'):
    if td.has_attr('class'):
        print(td['class'][0])

需要注意的是,即使属性只有一个值,属性键也会检索一个列表。

.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']