Python中的Selenium无法打开Chrome网址
当浏览器打开时,它就停在那里不动,什么也不做。driver.get(url)
这个命令没有发出请求,浏览器里也没有任何反应。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
import time
chrome_executable_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
# path to the chrome profile to get the logged google acc
chrome_profile_dir = r"C:\Users\myuser\AppData\Local\Google\Chrome\User Data\Profile 3"
# use the chrome profile
chrome_options = Options()
chrome_options.add_argument(f"user-data-dir={chrome_profile_dir}")
service = ChromeService(executable_path=chrome_executable_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
# this doesn't work, but it's not related to the url/nothing after this
url = "https://docs.google.com/forms/d/e/myformid/viewform?usp=pp_url&entry.1824=abc&entry.20988=def&entry.1589=123"
driver.get(url)
time.sleep(10)
submit_button = driver.findElement(By.xpath("//span[text()='Enviar']"))
submit_button.click()
# wait for form submission
time.sleep(10)
driver.quit()
我觉得这和Chrome的启动器有关。我必须使用完整的Chrome实例,因为我需要共享谷歌的会话,这样才能用我的谷歌账号发送谷歌表单。
我想做的是提交一个预填好的谷歌表单。我不知道怎么才能用我当前的会话去发送请求到/formresponse,所以我想直接使用已经登录的实例。
2 个回答
1
你的问题是因为需要指定ChromeDriver的路径,而不是Chrome浏览器本身的路径。
你需要下载ChromeDriver,并把这个文件的路径提供给executable_path。在你的代码中,应该使用ChromeDriver的路径,而不是chrome_executable_path。
另外,使用find_element
而不是findElement
。做了这些修改后,你的浏览器就能打开你想要的网址并执行操作了。
2
你的代码有几个问题:
executable_path
参数应该填写chromedriver.exe
的路径,而不是chrome.exe
的路径。
下面这行是错误的:
chrome_executable_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
应该改成这样:
chrome_executable_path = r"C:\full path\chromedriver.exe"
说到这里,你可以使用 Selenium Manager,这样就不用手动设置驱动了。下面的回答可能会对你有帮助:
https://stackoverflow.com/a/76463081/7598774
- 下面这行有语法错误。
submit_button = driver.findElement(By.xpath("//span[text()='Enviar']"))
应该是:
submit_button = driver.find_element(By.XPATH, "//span[text()='Enviar']")
- 最后,你的代码里缺少下面这个导入语句:
from selenium.webdriver.common.by import By