尝试使用API打印Yahoo搜索结果时,For循环计数器不会打印其递增值。解析并打印XML,但计数器反复打印“1”。
相同的代码适用于Bing API。
for counter1 in range(50):
try:
for Result in YahooSearchResultsXML.getElementsByTagName('Result'):
try:
Yahoo_PageTitle = Result.getElementsByTagName('Title')[counter1].firstChild.toxml(encoding="utf-8")
except AttributeError:
Yahoo_PageTitle = "Sorry, no page title provided..."
try:
Yahoo_PageDesc = Result.getElementsByTagName('Summary')[counter1].firstChild.toxml(encoding="utf-8")
except AttributeError:
Yahoo_PageDesc = "Sorry, no page description provided..."
Yahoo_DisplayURL = Result.getElementsByTagName('DisplayUrl')[counter1].firstChild.toxml(encoding="utf-8")
Yahoo_URL = Result.getElementsByTagName('ClickUrl')[counter1].firstChild.toxml(encoding="utf-8")
## Print the output to ensure it's working.
print counter1+1
print "<br />"
print "<h2>" + Yahoo_PageTitle + "</h2>"
print Yahoo_PageDesc + "<br />"
print Yahoo_DisplayURL + "<br />"
print Yahoo_URL + "<br />"
print "<p> ----------------------------------------------------------------------------------------------------------------- </p>"
except IndexError:
print "Exiting@IndexError handler"
break
Yahoo_Score = counter1 + 1
建议赞赏,现在看这段代码已经太久了。
答案 0 :(得分:0)
如上所述,打印在for Result in..
循环中。如果您有多重结果,则会获得具有相同内容的多行。
此外,(已修复)try
不应缩进?
编辑:从我们收集的信息中,您需要在内部循环中递增该计数器。你写它的方式(for counter1 in range(50)
)会在外循环中增加它。
试试这个(注意身份变化):
counter1 = 0
try:
for Result in YahooSearchResultsXML.getElementsByTagName('Result'):
try:
Yahoo_PageTitle = Result.getElementsByTagName('Title')[counter1].firstChild.toxml(encoding="utf-8")
except AttributeError:
Yahoo_PageTitle = "Sorry, no page title provided..."
try:
Yahoo_PageDesc = Result.getElementsByTagName('Summary')[counter1].firstChild.toxml(encoding="utf-8")
except AttributeError:
Yahoo_PageDesc = "Sorry, no page description provided..."
Yahoo_DisplayURL = Result.getElementsByTagName('DisplayUrl')[counter1].firstChild.toxml(encoding="utf-8")
Yahoo_URL = Result.getElementsByTagName('ClickUrl')[counter1].firstChild.toxml(encoding="utf-8")
## Print the output to ensure it's working.
print counter1+1
counter1 += 1
print "<br />"
print "<h2>" + Yahoo_PageTitle + "</h2>"
print Yahoo_PageDesc + "<br />"
print Yahoo_DisplayURL + "<br />"
print Yahoo_URL + "<br />"
print "<p> ----------------------------------------------------------------------------------------------------------------- </p>"
except IndexError:
print "Exiting@IndexError handler"
break
Yahoo_Score = counter1 + 1
答案 1 :(得分:0)
您确定每个Title
中有多个Summary
/ DisplayUrl
/ ClickUrl
/ Result
?当计数器的值达到1时,如果XML中某处没有第二个Title
/ etc元素,您将跳转到IndexError
处理程序并退出循环。