【问题标题】:Python Selenium Cannot find the href when it is on the websitePython Selenium 在网站上找不到href
【发布时间】:2019-07-12 07:52:07
【问题描述】:

我很难在这个特定网站上找到社交媒体链接: 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() 不是默认等待页面加载吗?

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

【问题讨论】:

    标签: python-3.x selenium error-handling


    【解决方案1】:

    网站在滚动时加载内容,这就是为什么要访问您需要滚动到页面底部的社交媒体帐户。
    要等待某些条件,您必须使用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)
    

    【讨论】:

    • 感谢您的回答!向下滚动似乎无法到达页面底部(也许它是“无限地”加载的?)我不知道为什么 WebDriverWait 在此页面中不起作用。我在这个答案中结合了投票最高的答案:stackoverflow.com/questions/20986631/…。我最后将更新的代码放在问题中。您介意检查一下为什么 WebDriverWait 在这种情况下不起作用吗?
    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多