我想使用selenium chromedriver来填充登录&但是,在https://www.asiamiles.com/en/login.html中,我发现只有在不将.add_argument设置为"——headless">
时,.find_elemen_by_xpath才能工作。我猜输入得到隐藏,如果我在后台运行chromedriver…
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:
#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)
有人知道为什么吗?谢谢。
尝试这样设置参数
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)
首先可以使用一个简单的xpath。下一个问题是,当运行无头时,网站可能会捡起你的一个机器人。
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()
进口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
<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>