python-3.x - Python Selenium 在网站上找不到 href

标签 python-3.x selenium error-handling

我很难找到这个特定网站上的社交媒体链接: https://www.digitalrealty.com/

我使用的代码:

url = 'https://www.digitalrealty.com/'
driver.get('https://www.digitalrealty.com/')
fb_link = driver.find_element_by_css_selector("a[href*='facebook.com']").get_attribute("href")

但是,在运行代码后,python 返回“NoSuchElementException”。事实上,当我查看网站并向下滚动时,社交媒体帐户就在底部。不知道是不是因为页面没有加载完全?但是 .get() 不是默认等待页面加载吗?

对于处理这些错误我还是新手。任何帮助,将不胜感激。提前致谢!

最佳答案

网站通过滚动加载内容,这就是为什么要访问社交媒体帐户,您需要滚动到页面底部。
要等待某些条件,您必须使用 WebDriverWaitexpected_conditions,有关等待的更多详细信息,您可以找到 here .

这是您的代码:

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

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)

url = "https://www.digitalrealty.com/"

driver.get(url)

#Scroll to the bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

#Wait until presence of the facebook element. Presence of element=exist in the DOM, but can be not visible like here.
facebook = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "a[href*=facebook]")))

#Scroll to element will make element visible and we'll able to click or get text, attribute from it
driver.execute_script("arguments[0].scrollIntoView(true);", facebook)

#Wait for facebook element to be visible and click on it.
fb = wait.until(EC.visibility_of(facebook)).get_attribute("href")
print(fb)

关于python-3.x - Python Selenium 在网站上找不到 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54755592/

相关文章:

python-3.x - 如何从 python 中激活 pyvenv vitrualenv? (activate_this.py 被删除了?)

python - scipy.interpolate.interp1d 'kind' 不工作

php - PHP 中的错误处理

ios - 我在 Xcode 中更改了我的项目名称,现在当我运行它时出现错误

selenium - 如何让 phpunit 在外部存储库上进行代码覆盖?

php - PHP警告消息公开了OAuth应用的 secret

python - sklearn ShuffleSplit "__init__() got multiple values for argument ' n_splits '"错误

python - 限时输入?

javascript - 找不到模块 - 相对路径

java - "java.lang.Error: Unresolved compilation problems"在使用 Maven 使用 TestNG 执行 Selenium 测试期间