我很难找到这个特定网站上的社交媒体链接: 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() 不是默认等待页面加载吗?
对于处理这些错误我还是新手。任何帮助,将不胜感激。提前致谢!
最佳答案
网站通过滚动加载内容,这就是为什么要访问社交媒体帐户,您需要滚动到页面底部。
要等待某些条件,您必须使用 WebDriverWait
和 expected_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/