【问题标题】:Python selenium's is_element_present is giving "wrong" answerPython selenium iselementpresent 给出了“错误”的答案
【发布时间】:2012-12-08 12:45:46
【问题描述】:

我正在尝试抓取一个页面,如果存在数据,该页面具有以下“表格视图”元素:

<div class="floatRight">
   <a id="MainContent_TabContainerUsageAndCost_TabPanelGasUsage_GasUsageView_UCGasUsage_lnkTableView2" title="Table View" href="javascript:__doPostBack(&#39;ctl00$ctl00$MainContent$TabContainerUsageAndCost$TabPanelGasUsage$GasUsageView$UCGasUsage$lnkTableView2&#39;,&#39;&#39;)" style="color:NoColor;">Table View</a>

</div>

否则,页面有以下错误信息。

<div class="error display">
                <span id="MainContent_TabContainerUsageAndCost_TabPanelElectricityUsage_ElectricityUsageView_UCElectricityUsage_lblMesg" style="font-weight:bold;">The account selected has no usage and costs data currently to be displayed.</span>

</div>

在 selenium 中,我试图在开始抓取数据之前检查上述两个条件。我尝试了以下方法:

if self.selenium.is_element_present('link=Table view'):
   self.selenium.click('link=Table view')
else:
   return []  # data not found

但是,“if”语句总是返回“true”,因此即使页面没有“表格视图”链接/元素,也会调用“点击”。

于是,我改写了代码来检查错误信息,如下:

if self.selenium.is_element_present('MainContent_TabContainerUsageAndCost_TabPanelElectricityUsage_ElectricityUsageView_UCElectricityUsage_lblMesg'):
    return []  # data not found
else:
    self.selenium.click('link=Table view')

现在,“if”语句总是返回 false,所以“click”在不应该被调用的时候被调用了!

显然,我没有正确使用 is_element_present。请指教。

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    在 Se-RC 中,您的脚本可以向元素发送点击事件,即使它们对用户不可见——它们只需要在 DOM 中即可。在 Se-WebDriver 中,元素也必须对用户可见。如果没有看到您正在抓取的页面的完整 HTML,就无法进一步诊断。

    【讨论】:

    • 谢谢——这很有帮助。我能够解决这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多