检查互联网按钮,无论是否检查都会打印一条消息

问题描述 投票:0回答:1

我正在尝试做以下练习:在Python上打开此页面,并检查“远程合格”按钮打开时会发生什么;有没有显示位置?

到目前为止,我有这段代码,但给我这个错误:无法找到或单击“远程合格”按钮:消息:没有这样的元素:无法找到元素:{“method”:“css选择器”,“selector” :"[id="c1853"]"}

当按钮关闭时,CSS 选择器为:

<input class="VfPpkd-muHVFf-bMcfAe" type="checkbox" id="c473" jsname="YPqjbf" jsaction="focus:AHmuwe; blur:O22p3e;change:WPi0i;" data-indeterminate="false">

当它打开时,它是:

<input class="VfPpkd-muHVFf-bMcfAe" type="checkbox" id="c556" jsname="YPqjbf" jsaction="focus:AHmuwe; blur:O22p3e;change:WPi0i;" data-indeterminate="false" checked=""> 

如何增强我的代码?

# !apt-get update
# !apt install chromium-chromedriver
# !pip install selenium

# Import necessary libraries
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Configure Selenium to use headless Chrome
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.binary_location = "/usr/bin/chromium-browser"

# Initialize WebDriver with options
driver = webdriver.Chrome(options=chrome_options)

# Open the webpage
driver.get("https://www.google.com/about/careers/applications/jobs/results?location=Chile&location=Santiago%2C%20Chile")

# Wait for the page elements to load
time.sleep(5)  # Adjust the sleep time based on your network speed

# Attempt to locate and click the "Remote eligible" button if it's present
# Note: You'll need to adjust the selectors based on the actual page structure
try:
    # Locate the checkbox element
    checkbox_element = driver.find_element(By.ID, 'c1853')
    
    # Check the value of the 'checked' attribute to determine if the button is on or off
    is_button_on = checkbox_element.get_attribute('checked')
    
    # Click the button only if it's off
    if not is_button_on:
        checkbox_element.click()
        print("Clicked 'Remote eligible' to turn it on.")
        time.sleep(3)  # Wait for the page to update after clicking

except Exception as e:
    print(f"Could not find or click 'Remote eligible' button: {e}")

# Now check if there are no positions displayed
# Adjust the method of checking based on how the webpage indicates no positions are available
no_positions_indicator = driver.find_elements(By.XPATH, '//div[contains(text(), "No positions found")]')
if no_positions_indicator:
    print("No remote and/or hybrid positions are displayed.")
else:
    print("Remote and/or hybrid positions are displayed.")

# Close the WebDriver
driver.quit()
python html css selenium-webdriver web-scraping
1个回答
0
投票

看起来 ID 是在每次页面加载时动态生成的。您可以使用 CSS 选择器来代替使用 ID。只有一个输入是复选框。

checkbox_element = driver.find_element(By.CSS_SELECTOR, 'input[type="checkbox"]')
© www.soinside.com 2019 - 2024. All rights reserved.