【问题标题】:How to print a message, when error message is displayed on website selenium如何在网站 selenium 上显示错误消息时打印消息
【发布时间】:2020-04-25 21:18:06
【问题描述】:

您好,我正在尝试使用 selenium 抓取网站,但有时该网站会阻止我的 ip 进行抓取并出现弹出消息。

我想要做的是,每当弹出消息出现时,它都会在我的终端上显示一个警告,我的代码看起来像这样以获得结果

blo = driver.find_element_by_xpath('/html/body/div[2]/div/div/div[1]/h3')
if blo:
    print('ip blocked')
else:
    print('eroor')

但它不工作我只是得到一个空白屏幕,我该如何解决这个问题

元素的HTML:

<h3 class="modal-title">Notifications</h3>
<div class="alert alert-warning">Sorry, you have exceeded the maximum number of queries allowed per day. If you believe you have reached this message in error, please contact our support team.</div>

【问题讨论】:

  • 添加等待获取blo元素。如果元素,则显示您的错误
  • 没有没有用
  • blo = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div/div[1]/h3')))你试过这个吗?
  • @walrus_run 请记住标记解决您问题的答案。见stackoverflow.com/help/someone-answers

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

验证是否存在 弹出消息,您必须为 visibility_of_element_located() 诱导 WebDriverWait,您可以使用以下任一 Locator Strategies: p>

  • 使用CSS_SELECTOR

    try:
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "h3.modal-title+div.alert.alert-warning")))
        print("ip blocked")
    except TimeoutException:
        print("eroor")
    
  • 使用XPATH

    try:
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h3[@class='modal-title' and text()='Notifications']//following::div[@class='alert alert-warning']")))
        print("ip blocked")
    except TimeoutException:
        print("eroor")
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2020-12-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多