使用 Selenium 单击没有 class、id 或 link 文本的 href 按钮

Click a href button with no class, id or link text with Selenium

我正在抓取网页:www.ogimet.com,我想单击 href 按钮。

这是 html 代码:

<a href="/sondc.phtml"><b>S</b>ondeos por territorios</a>

我怎样才能点击这个按钮?如果可以避免 driver.find_element_by_xpath()

这是我的做法,我创建了一个可重复使用的函数,returns 第一个元素通过标签和匹配属性。

def getElementByTagAndAttributes(driver, tag, **kwargs):
    for element in driver.find_elements_by_tag_name(tag):
        for key, value in kwargs.items():
            attribute = element.get_attribute(key)
            if attribute != value:
                break
        else:
            return element

getElementByTagAndAttributes(driver, "a", href="/sondc.phtml").click()

您提供的 link 确实有一个 link 文本可以用于 select 它,您只需要删除粗体标签,所以 Sondeos por territorios 代替共 <b>S</b>ondeos por territorios.

使用driver.find_element_by_link_text

link = driver.find_element_by_link_text('Sondeos por territorios')