javascript - 如何在 python 中使用 selenium 驱动程序单击链接而不知道 anchor 标记内的文本

标签 javascript jquery python selenium xpath

我使用selenium+phantomJS+scrapy scrapy javascript 内容。我想在加载 javascript 内容后单击表中的链接。但最重要的是,随着输入内容的不同,我要点击的链接也发生了变化。

然后我想使用xpath来定位链接,但失败了。这是我编写的 html 元素和 xpath。

<div class="results searchResults" style="display: block;”>
    <table cellspacing="0" id="resultGroup">
        <colgroup>
            <col width="4.216%">
            <col width="43.13%">
            <col width="52.65%">
        </colgroup>
        <tbody>
            <tr class="">
                <td class="selector">
                    <a href="#" id="c_2441797" title="Apple Inc." class="checkbox unchecked">&nbsp;</a>
                </td>
                <td class="name">
                    <div>
                        <a href="#!search/profile/company?companyId=2441797&amp;targetid=profile" class="companyResultsName">Apple Inc.</a>
                        <a href="http://www.google.com/finance?client=ob&amp;q=NASDAQ: AAPL" rel="external" target="_blank">(NASDAQ: AAPL)</a>
                    </div>

xpath 是 self.driver.find_element_by_xpath(".//*[@id='resultGroup']/tbody/tr[@class='name']/div[1]/a[@class='companyResultsName']").click()

希望有人能给我提示。谢谢。

最佳答案

如果您的元素是由 JavaScript 动态生成的,您应该等到它出现在 DOM 中:

 from selenium.webdriver.common.by import By
 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.support import expected_conditions as EC

 link = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "companyResultsName")))
 link.click()

关于javascript - 如何在 python 中使用 selenium 驱动程序单击链接而不知道 anchor 标记内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41758059/

相关文章:

python - 在 Pyglet 中有没有办法将 Sprite 带到前台

python - 如何让用户只能编辑自己创建的对象?

javascript - Jquery 始终还原可拖动对象有效

javascript - 无法使用 AngularJs 获取文本区域值

javascript - 如何让webGL扭曲它下面的HTML?

javascript - Material ui 表行复选框不显示

JavaScript/jQuery : How do you pass an element to a function as its 'this' ?

javascript - 在javascript中打印元素宽度

python - Python 的三引号字符串是如何工作的?

javascript - 在新选项卡中打开一个链接,打开另一个链接并在该选项卡上重新加载