python爬虫问题

DO_HZH 2019-11-09 11:32:10

各位好,我在做python爬虫的时候遇到了这个弹出框的问题。
这个弹出框是当无法搜索到小说时,页面会打开一个新的标签并且提示你是不是关键字有误。我试过了selenium的alert.accept,但是无法做到对弹出框点击确定。以下是我的代码
from bs4 import BeautifulSoup
import urllib.request as request
from selenium import webdriver
from w3lib import html as h #摘除标签和特定标签的内容
from time import sleep
import re
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.common.keys import Keys
#搜索小说
driver = webdriver.Chrome()
driver.maximize_window()
fake_adress = "https://www.xbiqugexsw.com"
driver.get(r'https://www.xbiqugexsw.com')
main_windows = driver.current_window_handle
#进入搜索栏
input_search = driver.find_element_by_class_name('search')
input_search.send_keys('bilibili')
sleep(1)
button_search= driver.find_element_by_tag_name('button')
button_search.click()
sleep(3)
try:
all_handle1 = driver.window_handles
print(all_handle1)
for pay_handle1 in all_handle1:
if pay_handle1 != main_windows:
driver.switch_to.window(pay_handle1)
alert0 = driver.switch_to.alert
print(alert0)
alert0.accept()
except NoAlertPresentException:
print('noalert')

请问是哪里有问题吗?求赐教
...全文
106 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
DO_HZH 2019-11-09
  • 打赏
  • 举报
回复
引用 1 楼 cool_soup29 的回复:
你这个window_handles,是多窗口之间的切换的,不是切换到这个通知层的. 我建议给出的方法: 1.禁用通知这个功能 option = webdriver.ChromeOptions() option.add_argument("--disable-popup-blocking") 2.选择键盘操作模块

import virtkey
v = virtkey.virtkey()
v.press_keysym(65421)  # Enter
time.sleep(0.5)
v.release_keysym(65421) #松开
谢谢大佬,我去试试。可是我没有找到virtkey这个库,是windows没法装吗?
cool_soup29 2019-11-09
  • 打赏
  • 举报
回复
你这个window_handles,是多窗口之间的切换的,不是切换到这个通知层的. 我建议给出的方法: 1.禁用通知这个功能 option = webdriver.ChromeOptions() option.add_argument("--disable-popup-blocking") 2.选择键盘操作模块

import virtkey
v = virtkey.virtkey()
v.press_keysym(65421)  # Enter
time.sleep(0.5)
v.release_keysym(65421) #松开
cool_soup29 2019-11-09
  • 打赏
  • 举报
回复
引用 1 楼 cool_soup29 的回复:
你这个window_handles,是多窗口之间的切换的,不是切换到这个通知层的. 我建议给出的方法: 1.禁用通知这个功能 option = webdriver.ChromeOptions() option.add_argument("--disable-popup-blocking") 2.选择键盘操作模块

import virtkey
v = virtkey.virtkey()
v.press_keysym(65421)  # Enter
time.sleep(0.5)
v.release_keysym(65421) #松开
噢,这样,我用ubuntu的,直接安装就有了,window的话你可以用那个pykeyboard模块就好了

#pip3 install pykeyboard
from pykeyboard import PyKeyboard
import time
k=PyKeyboard()
k.press_key(k.enter_key)
time.sleep(0.1)
k.release_key(k.enter_key)

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧