我如何等待使用Python中的selenium加载此网站?

2024-09-30 01:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在python web抓取项目中使用beautifulSoup。然而,在我需要抓取的一个页面中,我需要与javascript元素交互。所以我不得不使用硒(我不太熟悉)。 这是我目前的代码:

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
opts = Options()
opts.add_argument('--headless')
seleniumDriver = Firefox(options=opts, executable_path = 'D:\Programs\Python\Scripts\geckodriver.exe')

seleniumDriver.get("https://www.thecompleteuniversityguide.co.uk/courses/details/computing-bsc/57997898")
driverWait = WebDriverWait(seleniumDriver, 10)
driverWait.until(EC.invisibility_of_element_located((By.ID, "mainBody")))

moduleButton = seleniumDriver.find_element_by_xpath("//div[@class='mdldv']")#.find_element_by_tag_name("span")
print("MODULE BUTTON:", moduleButton)
moduleButton.click()

seleniumDriver.close()

目前,我收到一个超时错误,但是我确定mainBody ID元素确实存在。 (我不知道如何使用By类,所以我不知道它将如何工作)。 错误消息:

Traceback (most recent call last):
  File "D:/Web Scraping/selenium tests.py", line 12, in <module>
    driverWait.until(EC.invisibility_of_element_located((By.ID, "mainBody")))
  File "D:\Programs\Python\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

Tags: fromimportidsupportbyseleniumelementuntil
1条回答
网友
1楼 · 发布于 2024-09-30 01:30:11

您的电话是:

driverWait.until(EC.invisibility_of_element_located((By.ID, "mainBody")))

根据文档,这将等待元素消失:

class invisibility_of_element_located(object):
    """ An Expectation for checking that an element is either invisible or not
    present on the DOM.

    locator used to find the element
    """

引发的超时异常意味着该元素已找到,但从未从DOM中删除,也从未变为不可见

在找到元素(DOM的一部分)之前需要等待的内容。改用,presence_of_element_located

driverWait.until(presence_of_element_located((By.ID, "mainBody")))

如果在创建driverWait时请求的超时内未找到timeout异常,则将引发该异常

(我不知道如何使用By类,所以我不知道它将如何工作)

当通过xpath/id/css\u选择器调用find\u元素时,By在引擎盖下使用

在您的情况下,当您使用EC时,您将提供定位器以使用By.ID及其值。您可以看到它等于find_element_by_id('yourValue')

相关问题 更多 >

    热门问题