问题描述
我已经在 Chrome 正常模式下使用 python selenium 完成了我的自动化脚本,一切正常。
直到我决定让它在无头模式下工作,所以现在我找不到已经在正常模式下工作的部分链接文本。
我正在使用此代码在 headless 中打开 chrome。
option = webdriver.ChromeOptions()
option.headless = True
option.AddArgument("window-size=1200,700");
这是我用来定位元素的代码
tmp = True
while tmp:
try:
Confirmm = driver.find_element_by_partial_link_text('Confirm')
Confirmm.click()
tmp = False
except:
continue
<a href="https://temp-mail.org/en/view/346e2949a4a1f77ededd7542ba7947ed" title="" class="viewLink title-subject" data-mail-id="346e2949a4a1f77ededd7542ba7947ed">Confirm your profile</a>
注意:data-mail-id= 不是静态的,每次都会发生变化。
我尝试使用 Javascript,但我愿意点击的词没有 ID、NAME 或 TAG-NAME,并且 ClassName 也不起作用。
知道如何解决这个问题吗?
解决方法
要点击带有确认您的个人资料文本的元素,您可以使用以下任一Locator Strategies:
-
使用
link_text
:driver.find_element_by_link_text("Confirm your profile").click()
-
使用
partial_link_text
:driver.find_element_by_partial_link_text("Confirm").click()
-
使用
css_selector
:driver.find_element_by_css_selector("a.viewLink.title-subject[href^='https://temp-mail.org/en/view']").click()
-
使用
xpath
:driver.find_element_by_xpath("//a[@class='viewLink title-subject' and starts-with(@href,'https://temp-mail.org/en/view')][contains(.,'Confirm your profile')]").click()
理想情况下,要单击需要为 element_to_be_clickable()
引入 WebDriverWait 的元素,您可以使用以下任一 Locator Strategies:
-
使用
LINK_TEXT
:WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.LINK_TEXT,"Confirm your profile"))).click()
-
使用
PARTIAL_LINK_TEXT
:WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT,"Confirm"))).click()
-
使用
CSS_SELECTOR
:WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"a.viewLink.title-subject[href^='https://temp-mail.org/en/view']"))).click()
-
使用
XPATH
:WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//a[@class='viewLink title-subject' and starts-with(@href,'Confirm your profile')]"))).click()
-
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
尝试获取页面的屏幕截图并验证链接是否可用。有时网站会检测无头浏览器并以不同方式显示网站。
driver.get_screenshot_as_file(f"screenshot.png")
如果显示的网站不同,则设置自定义自定义标题(因为网站使用用户代理检测浏览器是无头的):
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--window-size=1920,1080")
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument(
"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/87.0.4280.88 Safari/537.36")
browser = webdriver.Chrome(options=options)
也使用 webdriver 等待:
WebDriverWait(driver,15).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT,"Confirm"))).click()