当网站上显示错误消息时,如何打印消息

2024-04-25 17:05:31 发布

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

嗨,我正在尝试使用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>

Tags: 代码ipdivyou终端消息警告网站
1条回答
网友
1楼 · 发布于 2024-04-25 17:05:31

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

  • 使用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")
    

相关问题 更多 >

    热门问题