我遇到一个错误,说“ del ports_db_names [0]”处不存在该索引,但该索引处有一个变量
代码的前6行是我要通过函数执行的操作,因为我希望能够从列表中添加或删除列表,并且仍然能够将所有变量转换为字符串。我尝试执行str(ports_db_names),但是当我尝试在函数中使用它时似乎不起作用,但是当我手动将它们转换为字符串时,它起作用了。
connection_url_1 = (str(ports_db_names[0]))
connection_url_2 = (str(ports_db_names[1]))
connection_url_3 = (str(ports_db_names[2]))
connection_url_4 = (str(ports_db_names[3]))
#this list is what I want to create through a function by converting each connection_url tag to a string
list = [connection_url_1, connection_url_2, connection_url_3, connection_url_4]
#########################################################
import bs4 as bs
import lxml
#used for increments
plus_1 = 1
#opens and parses the domain.xml file
xml_file = open('domain.xml')
soup = bs.BeautifulSoup(xml_file, 'lxml')
#creates a list containing all the connection-url tags
ports_db_names = (soup.find_all('connection-url'))
#function for converting variables in list into string
def connection_urls(x):
# creates an list
connection_urls = []
#number used for naming the variables
n = 1
#used to iterate through the list
i = len(ports_db_names)
#used to iterate through list until there are no more variables to go through
while (i > 0):
#renames each variable to "connection_url_" and the a number is added to insure the order
x = "connection_url_" + str(n)
#adds the variable to a new list
connection_urls.append(x)
#increments n so that the next connection_url_ is one number above the previous
n = n + plus_1
#deletes the variable at index 0 from the original list so that the next variable can go through the function just like the previous variable
del ports_db_names[0]
#when i is = 0 meaning all the variables went through the function it will return the array with all the variables converted to strings.
else:
return connection_urls
print (connection_urls(ports_db_names))
###############################################################################
#this is the contents of the xml file I parsed and I named it domain.xml
<connection-url>jdbc:oracle:thin:@test1:1675</connection-url>
<connection-url>jdbc:oracle:thin:@test2:1345</connection-url>
<connection-url>jdbc:oracle:thin:@test3:1434</connection-url>
<connection-url>jdbc:oracle:thin:@test4:1755</connection-url>
答案 0 :(得分:0)
我不是100%知道您要寻找什么,但这有帮助吗?
import bs4 as bs
# opens and parses the domain.xml file
with open('domain.xml') as xml_file:
soup = bs.BeautifulSoup(xml_file, 'lxml')
# creates a list containing all the connection-url tags
ports_db_names = soup.find_all('connection-url')
ports_db_names = map(str, ports_db_names)
这将从XML文件中恢复所有连接URL标记,并将它们转换为字符串列表。
然后,您可以按照自己喜欢的任何方式打印它们。
print("\n".join(ports_db_names))