首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当.add_argument(“--无头”)时,Chromedriver无法检索元素?

当.add_argument(“--无头”)时,Chromedriver无法检索元素?
EN

Stack Overflow用户
提问于 2021-02-24 07:43:12
回答 2查看 116关注 0票数 0

我想使用selenium色度驱动器来填充https://www.asiamiles.com/en/login.html中的登录名& pw,但是,我发现只有当我没有将.add_argument设置为“-无头”时,.find_elemen_by_xpath才能工作。

我猜如果我在后台运行色度驱动器,输入就会隐藏起来.

代码语言:javascript
运行
复制
asia_miles_url = 'https://www.asiamiles.com/en/login.html'
driver         = ws_functions.get_ChromeDriver(()) #it works
# driver         = ws_functions.get_ChromeDriver(("--headless")) #it doesn't work
driver.implicitly_wait(30)
driver.get(asia_miles_url)
time.sleep(8)
driver.find_element_by_xpath('/html/body/div[3]/div/div/div/div[2]/div/form/div[2]/div[1]/div[1]/div/input').send_keys('abc')
time.sleep(1)
driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div/div[2]/div/form/div[2]/div[1]/div[2]/div/input').send_keys(password)
time.sleep(0.5)
driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div/div[2]/div/form/div[2]/div[1]/div[3]/div[3]/button').click()

我在ws_functions中的自定义函数

代码语言:javascript
运行
复制
#Get ChromeDriver
def get_ChromeDriver(*headless): #turple headless = null -> Chrome runs in foregound
chrome_options  = Options()
if headless[0] == "--headless":
    chrome_options.add_argument("--headless")
chrome_options.add_argument("window-size=1920,1080")
return webdriver.Chrome(executable_path=settings.chromedriver,options=chrome_options)

有人知道为什么吗?谢谢。

EN

回答 2

Stack Overflow用户

发布于 2021-02-24 08:13:15

尝试像这样设置参数

代码语言:javascript
运行
复制
from selenium.webdriver.chrome.options import Options
chrome_options = Options()

chrome_options.add_argument("--headless")
# chrome_options.headless = True # also works
driver = webdriver.Chrome(options=chrome_options)

start_url = "<Your URL>"
driver.get(start_url)
票数 0
EN

Stack Overflow用户

发布于 2021-02-24 10:30:48

首先,这里有一个您可以使用的简单xpath。下一个问题是,当运行无头时,站点可能会发现您的机器人。

代码语言:javascript
运行
复制
wait = WebDriverWait(driver, 10)
driver.get('https://www.asiamiles.com/en/login.html')
wait.until(EC.element_to_be_clickable((By.XPATH,"(//input[@id='username'])[2]"))).send_keys('abc')
wait.until(EC.element_to_be_clickable((By.XPATH,"(//input[@id='password'])[2]"))).send_keys(password)
wait.until(EC.element_to_be_clickable((By.XPATH,"(//button[.='Log in'])[3]"))).click()

导入

代码语言:javascript
运行
复制
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

如果你打印driver.page_source

代码语言:javascript
运行
复制
<html><head>
<title>Access Denied</title>
</head><body>
<h1>Access Denied</h1>
 
You don't have permission to access "http://www.asiamiles.com/en/login.html" on this server.<p>
Reference #18.869a3b17.1614165148.2921fb4b


</p></body></html>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66346610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档