我想自动点击网站并搜索信息,但不知何故,网站无法搜索,并不断加载。或者在它打印出搜索栏中的键后迅速关闭。
我想自动点击网站并搜索信息,我尝试过:
import selenium
import pandas as pd
import numpy as np
import platform
import time
import random
from os import getcwd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-notification")
options.add_argument("--disable-infobars")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument("--remote-debugging-port=9230")
#options.add_argument("--headless")
url = 'https://vip.stock.finance.sina.com.cn/mkt/#hs_z'
driver.get(url)
w = WebDriverWait(driver, 10)
w.until(EC.presence_of_element_located((By.XPATH, '//*[@id="inputSuggest"]')))
driver.find_element('xpath', '//*[@id="inputSuggest"]').clear()
driver.find_element('xpath', '//*[@id="inputSuggest"]').send_keys('sz111973'))
driver.find_element('xpath', '//*[@id="SSForm"]/input[3]').click()
但不知何故,网站无法搜索,并不断加载。或者在它打印出搜索栏中的键后迅速关闭。任何帮助都将不胜感激!谢谢
这里有几个问题:
- 为了防止站点加载时间过长,您可以使用
eager
pageLoadStrategy
- 我在这一行的末尾看到了冗余的
)
driver.find_element('xpath', '//*[@id="inputSuggest"]').send_keys('sz111973'))
以下代码非常有效:
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "eager"
webdriver_service = Service('C:webdriverschromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options, desired_capabilities=caps,)
url = 'https://vip.stock.finance.sina.com.cn/mkt/#hs_z'
driver.get(url)
wait = WebDriverWait(driver, 20)
input = wait.until(EC.element_to_be_clickable((By.ID, 'inputSuggest')))
input.clear()
input.send_keys('sz111973')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#inputSuggest +input'))).click()