python - 使用 Selenium 和partial_link_text 抓取 html 元素

标签 python html python-2.7 selenium selenium-webdriver

我正在尝试使用 Firefox 驱动程序中 Selenium 的 driver.find_element_by_partial_link_text 来获取链接元素。

我使用它的原因是因为链接的全名会定期更改,但最后几个字符将始终保持不变。类似于:“[...] AL Changes.xlsx”

由于某种原因,我收到“NoSuchElementException:无法定位元素”错误

这是 html...

<a class="ms-listlink ms-draggable" onmousedown="return VerifyHref(this,event,'1','SharePoint.OpenDocuments','')" onclick="return DispEx(this,event,'TRUE','FALSE','FALSE','SharePoint.OpenDocuments.3','1','SharePoint.OpenDocuments','','','','2027','0','0','0xb008431061')" href="/sites/market/Market_And_Customer_Information/MCIR Library/01 2015 AL Changes.xlsx" DragId="3">01 2015 AL Changes</a>​

这是我的代码:

self.driver.get(url_path)
self.driverfind_element_by_partial_link_text('AL Changes.xlsx').click()

enter image description here

最佳答案

您将链接文本与 href 属性值混淆了。

您案例中的链接文本是“01 2015 AL Changes”:

self.driver.find_element_by_link_text('01 2015 AL Changes').click()
<小时/>

但是,如果您需要使用 href 属性来定位元素:

self.driver.find_element_by_css_selector('a[href$="AL Changes.xlsx"]').click()

其中 $= 表示“结尾为”。

<小时/>

您可能还需要等待链接变得可点击:

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

wait = WebDriverWait(driver, 10)
link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "01 2015 AL Changes")))
link.click()

关于python - 使用 Selenium 和partial_link_text 抓取 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31859710/

相关文章:

python - MySQL语句中的语法错误是什么?

jquery - HTML 列表框换行文本

html - 奇怪的 CSS 问题,内容单元在 IE 中移动到页面底部 - 在 Chrome 和 Firefox 中工作正常

python-2.7 - 使用 pika connection.close() 给出 "WARNING:pika.adapters.base_connection:Unknown state on disconnect: 0"

python - 将列表作为单个元素插入到元组中

python - 余弦相似度和句子

Python 请求模块不适用于带路径的 url

python - pandas.core.groupby.DataFrameGroupBy.idxmin() 非常慢,如何使我的代码更快?

python - 为seaborn的线图中图表下方的区域着色?

html - 如何使用 CSS 降低元素背景的不透明度?