【问题标题】:How to get the link from a clickable element in selenium python如何从 selenium python 中的可点击元素获取链接
【发布时间】:2017-11-14 10:07:40
【问题描述】:

我想从网站下载 CSV 文件。这就是我使用 selenium 中的click() 命令的原因。

元素具有以下结构


代码

 csvList = browser.find_elements_by_class_name("csv")
    for l in csvlist:
           if 'error' not in l.text and 'after' not in l.text:
               #get link here
               l.click()
               

问题

我的问题是如何在下载之前从元素中获取 下载链接?图中黑色箭头所指的链接。

当我使用 l.get_attribute('href') 时,它给了我 None。

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    div 没有 href 属性。它的父级是“a”标签。我会使用 xpath。

    By.XPath("//a[/div[@class='csv']]")
    

    【讨论】:

    • 我以后还能点击链接吗?
    • 是的,所以你可以按照 Timothy Cope 的建议去做。或者您可以在 FindElements 方法中使用它来查找链接。然后你可以在你的 for 循环中点击它们。
    • 我认为应该browser.find_elements_by_xpath('//div[@class="csv"]/parent::a')对吗?
    【解决方案2】:

    对于csvList中的每个元素l,通过xpath获取父元素,然后获取该元素的href

    csvList = browser.find_elements_by_class_name("csv")
    for l in csvlist:
           if 'error' not in l.text and 'after' not in l.text:
               currentLink = l.find_element_by_xpath("..")
               href = currentLink.get_attribute("href")
    

    注意:如果您在此循环中执行 .click() 并且链接会将您带到一个新页面,那么您将在第一次点击之后获得 StaleElementException。在这种情况下,提取每个 href 并保存到集合中。然后导航到集合中的每个 href (URL)。

    【讨论】:

    • 我收到以下错误 AttributeError: 'list' object has no attribute 'get_attribute'
    • 我更新了答案以显示您提供的循环中的代码。另外,我有 'find_elements' 而不是 'find_element' 所以我也改变了它。
    • 是的,它是一样的,没关系。文件 “QL2scrape.py”,第 84 行,在 href = currentLink.get_attribute("href") AttributeError: 'list' object has no attribute 'get_attribute''''
    • 你认为它得到了所有的父母吗?我应该使用 currentLink[0].get_attribute 吗?
    • 不确定。最好的办法是print他们看看。
    猜你喜欢
    • 2013-04-19
    • 2019-03-11
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    相关资源
    最近更新 更多