【问题标题】:Task done in python automation在 python 自动化中完成的任务
【发布时间】:2021-12-23 22:28:18
【问题描述】:

正如标题所说,我正在做一个我需要做的小项目 "打开链接,点击一个按钮,替换部分链接,然后重新做任务"

我的代码有点乱,我还是个新手,但到目前为止就是这样,我遇到的问题是当我添加“if else”函数时页面没有打开。页面无法打开,我可以不使用 if else,但由于按钮的 xpath 在随机编号的页面中发生变化,这是我能想到的唯一解决方案

PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()

button = driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div[2]/div[3]/div/div[2]/button")
button1 = driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div/div[3]/div/button")

for i in range(1,5):
    print(f"https://test.com/page/{i}")
    driver.get(f"https://test.com/page/{i}")
    if button is not None:
        button.click()
    else:
        button1.click()

【问题讨论】:

  • 您尝试在加载网站之前获取按钮。做 .get() 然后 .find_element 然后你可以检查是否按钮。此外,xpath 是“坏”的,使用类或某些属性来识别元素

标签: python selenium automation


【解决方案1】:

在获取按钮之前加载页面。另外,请确保使用此脚本加载按钮:

PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()

button_selector = "/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div[2]/div[3]/div/div[2]/button"
button1_selector = "/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div/div[3]/div/button"

for i in range(1, 5):
    print(f"https://test.com/page/{i}")

    # Load the page
    driver.get(f"https://test.com/page/{i}")

    # Get the buttons
    button = driver.find_element_by_xpath(button_selector) or None
    button1 = driver.find_element_by_xpath(button1_selector) or None
    time.sleep(1)  # Make sure the buttons are loaded

    if button is not None:
        button.click()
    elif button1 is not None:
        button1.click()


driver.quit() # Be sure to close the driver

【讨论】:

  • 谢谢你的回复马丁,我试过这段代码,现在至少页面加载了,但由于某种原因它停在那里,没有点击按钮。我确实尝试将“time.sleep”更改为 5-7,以防按钮未完全加载,但它仍然无法正常工作
  • 你确定选择器是正确的吗?难道按钮没有可以使它们更独特地访问的类或 ID?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2011-06-20
  • 1970-01-01
  • 2017-06-17
相关资源
最近更新 更多