如何在Python中使用Selenium驱动程序点击链接,同时不知道锚点标签内的文本

2024-05-28 18:06:35 发布

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

我使用selenium+phantomJS+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()

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


Tags: divid内容链接coljavascriptwidthxpath
1条回答
网友
1楼 · 发布于 2024-05-28 18:06:35

如果元素是由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()

相关问题 更多 >

    热门问题