selenium常用

mac2024-05-31  37

selenium实用方法

from selenium import webdriver from selenium.webdriver.chrome.options import Options #设置无头浏览器 def __init__(self): self.options = Options() self.options.add_argument('-headless') # 无头参数 self.driver =webdriver.Chrome(chrome_options=self.options,executable_path='E:\Python36\Scripts\chromedriver.exe') #搜索生成新窗口,切换到新窗口 self.driver.get(response.url) now_handle = self.driver.current_window_handle #会生成一个新窗口或新标签页的句柄,代表这个窗口的模拟driver self.driver.find_element_by_xpath("//input[@id='xhmc']").send_keys(f"{self.word}") # 搜索框输入 self.driver.find_element_by_xpath("//button[@type='submit']").click() # 点击搜索按钮,会出现一个新窗口或者新标签 time.sleep(2) all_handles = self.driver.window_handles # 获取所有窗口句柄 for handle in all_handles: #始终获得当前最后的窗口 self.driver.switch_to.window(handle) html = self.driver.page_source #切换到新窗口,获取新窗口页面的元素 在使用xpath时不需要直接求出text,否则会抛出错误。 应使用 result = chrome.find_element_by_xpath('//div[@id="transTarget"]/p/span') text = result.text
最新回复(0)