使用pythonbs4和lxm从xml中提取值

2024-04-18 14:55:23 发布

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

如何从下面的xml文件中提取侦听器的数量,我的代码无法工作。在

import bs4
import urllib2
import lxml
 bs4.BeautifulSoup(urllib2.urlopen('http://admin:mashytamam@192.168.0.31:8382/admin/').read(), 'lxml')    
SERVER = 'http://192.168.0.31:8382/admin/'
authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
authinfo.add_password(None, SERVER, 'admin', 'mypassword')
page = 'http://192.168.0.31:8382/admin/'
handler = urllib2.HTTPBasicAuthHandler(authinfo)
myopener = urllib2.build_opener(handler)
opened = urllib2.install_opener(myopener)
output = urllib2.urlopen(page)
print output.read()
soup = bs4.BeautifulSoup(output.read(), 'lxml')
print soup.find('listeners')

xml如下所示

^{pr2}$

Tags: importhttpreadoutputserveradminpagexml
2条回答

试试这个:

soup = BeautifulSoup(output.read(), 'xml')
for value in soup.find_all('listeners'):
    print(value.get_text())

使用这个:

soup = BeautifulSoup(output.read())
soup.select('listeners')
[<listeners>10</listeners>, <listeners>0</listeners>]

相关问题 更多 >