.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
просто используйте 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
Я бы на самом деле предложил вам сэкономить время, чтобы предположить, что вы знаете, какие теги имеют эти атрибуты.
предположим, что тег xyz имеет этот attritube с именем «staininfo» ..
full_tag = soup.findAll("xyz")
И я не пойму, что full_tag - это список
for each_tag in full_tag:
staininfo_attrb_value = each_tag["staininfo"]
print staininfo_attrb_value
Таким образом, вы можете получить все значения attrb staininfo для всех тегов xyz
Если вы хотите получить несколько значений атрибутов из источника выше, вы можете использовать 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.
вы также можете использовать это:
import requests
from bs4 import BeautifulSoup
import csv
url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})
for val in get_details:
get_val = val["value"]
print(get_val)
output = inputTag[0].contents
– Seth 12 April 2010 в 00:31inputTag[0].get('value')
вместоinputTag[0]['value']
, чтобы предотвратить отсутствие указателя в случае, если тег не имеет атрибута значения – amphibient 16 November 2016 в 20:33