gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:40:46 24 4
gpt4 key购买 nike

我在此特定网站上找不到社交媒体链接:
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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com