Selenium Python Paste在无头模式下不工作

2024-10-06 07:36:53 发布

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

Python selenium paste不是在headless模式下工作的,我尝试了CONTROL+V、SHIFT+INSERT和pyperclip3、pyperclip、klembord,但似乎没有任何效果,下面是代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import pyperclip3
import time

Desc = """<p><iframe src="https://www.youtube.com/embed/-grLLLTza6k" frameborder="0" allowfullscreen=""></iframe></p><p><img src="https://images-na.ssl-images-amazon.com/images/I/71Zxjh0AdpL.png" style="width:100%;max-width:450px;clear:both;"></p><p></p><h2>10 Undeniable Reasons People Hate cheats</h2>"""


options = Options()
options.binary_location = r'CHROME_BINARY_LOCATION'
options.add_argument("--headless")
webdriver.Chrome(executable_path=r'CHROME_DRIVER_LOCATION', options=options)
driver.implicitly_wait(10)
driver.get("http://google.com")
time.sleep(2)
pyperclip3.copy(Desc)
element = driver.find_element(By.XPATH, '//input[@name="q"]')
# element.send_keys(Keys.CONTROL, 'v')
a = pyperclip3.paste()
element.send_keys(Keys.SHIFT, Keys.INSERT)
element.send_keys(Keys.CONTROL, 'v')
time.sleep(2)
driver.save_screenshot("image.png")
driver.close()
driver.quit()

Tags: fromimportcomsendtimedriverseleniumelement
1条回答
网友
1楼 · 发布于 2024-10-06 07:36:53

我用显式等待尝试了下面的代码,它似乎用pyperclip完成了这项工作:

options = webdriver.ChromeOptions()
options.add_argument(" disable-infobars")
options.add_argument(" start-maximized")
options.add_argument(" disable-extensions")
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 2})
options.add_argument(' window-size=1920,1080')
options.add_argument(" headless")
options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2})
driver = webdriver.Chrome(executable_path=driver_path, options = options)
driver.implicitly_wait(30)
driver.maximize_window()
driver.get("http://google.com")
wait = WebDriverWait(driver, 20)

desc = '''<p><iframe src="https://www.youtube.com/embed/-grLLLTza6k" frameborder="0" allowfullscreen=""></iframe></p><p><img src="https://images-na.ssl-images-amazon.com/images/I/71Zxjh0AdpL.png" style="width:100%;max-width:450px;clear:both;"></p><p></p><h2>10 Undeniable Reasons People Hate cheats</h2>'''
pyperclip.copy(desc)
time.sleep(1)
wait.until(EC.visibility_of_element_located((By.NAME, 'q'))).send_keys(pyperclip.paste())
print("Succesful")
driver.save_screenshot("image.png")

导入:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import pyperclip as pyperclip
 

相关问题 更多 >