我的代码非常简单:单击 href 链接来下载文件。它工作正常,直到我添加 headless 参数,然后单击它不会执行任何操作。不确定这是 Selenium 问题还是 Chromedriver 问题?我在网上找到的解决方案都没有帮助,因此任何建议将不胜感激。这是我的代码:
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class Scraper(object):
def __init__(self, cursor):
self.driver = None
def create_driver(self):
# Set up Headless Chrome
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--window-size=1920x1080")
self.driver = webdriver.Chrome(executable_path=os.path.abspath("path to chromedriver"),
chrome_options=chrome_options)
self.driver.maximize_window()
def go_to_website(self):
self.driver.get('https://www.abs.gov.au/AUSSTATS/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d5c5f4e7d13534e5b" rel="noreferrer noopener nofollow">[email protected]</a>/DetailsPage/6202.0Nov%202019?OpenDocument')
link_to_click = self.driver.find_element_by_xpath("//a[contains(@href,'/log?openagent&6202012.xls&6202.0')]")
link_to_click.click()
def run(self):
# set a new driver
self.create_driver()
self.go_to_website()
最佳答案
如果您的用例是单击文本为 的元素的 .xls 元素...表 12. 按性别、州和地区划分的劳动力状况 - 趋势、季节性调整和原来...您要为element_to_be_clickable()
引发WebDriverWait,并且可以使用以下任一Locator Strategies :
使用
CSS_SELECTOR
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#details tbody tr:nth-of-type(13) td>a>img"))).click()
使用
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//tr[@class='listentry']/td[contains(., 'Labour force status by Sex, State and Territory - Trend, Seasonally adjusted and Original')]//following::td[1]/a/img"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
更新
但是,通过定位器策略单击该元素可能无法启动下载。使用 google-chrome-headless 启动下载你必须通过execute_cdp_cmd()
配置Page.setDownloadBehavior
,你可以在Download file through Google Chrome in headless mode中找到详细的讨论。
关于python - 元素在 headless 模式下不可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59808158/