我试图解析来自 url 调用的 html 输出,但我发现自己在努力解决如何让它工作。
我使用以下代码:
import urllib2
import base64 as b64
import lxml.html as LH
request = urllib2.Request('http://%s%s' % (fInput[1], fInput[2]))
base64string = b64.encodestring('%s:%s' % (fInput[3], fInput[4])).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
html = response.read()
root = LH.fromstring(html)
sibling_content = lambda x: [b.getparent().getnext().text_content() for b in root.cssselect("td b:contains('{0}')".format(x))]
fields = ['groupList','namelist']
for result in zip(*[sibling_content(field) for field in fields]):
print result
我打印输出时的结果是:
('Admins', '\nme\nmyself\nirene')('guests', '\nhin\nhinself\nbacon')
适合我需要的输出是有一个这样的数组,所以我可以将它插入数据库:
['Admins', 'me','myself','nirene'],['guests', 'hin','hinself','bacon']
接下来,我发送 HTTP 请求返回的 Html:
<BODY bgcolor="#dddddd">
<TABLE bgcolor="#dddddd" border="1">
<TR>
<TD valign="top"><B>MainList</B></TD>
<TD>
<TABLE>
<TR>
<TD>
<TABLE bgcolor="#dddddd" border="1">
<TR>
<TD valign="top"><B>groupList</B></TD>
<TD>Admins</TD>
</TR>
<TR>
<TD valign="top"><B>namelist</B></TD>
<TD>
<TABLE>
<TR>
<TD>me</TD>
</TR>
<TR>
<TD>myself</TD>
</TR>
<TR>
<TD>irene</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
<TABLE bgcolor="#dddddd" border="1">
<TR>
<TD valign="top"><B>groupList</B></TD>
<TD>guests</TD>
</TR>
<TR>
<TD valign="top"><B>namelist</B></TD>
<TD>
<TABLE>
<TR>
<TD>hin</TD>
</TR>
<TR>
<TD>hinself</TD>
</TR>
<TR>
<TD>bacon</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</BODY>
关于如何让这个工作的任何想法?
提前致谢。