我创建了一个机器人,可以使用 Selenium Python 自动更新 Shopify 上的产品价格。我告诉这个机器人找到价格元素并清除它,然后将新价格作为小数点后两位格式的字符串发送。例如184.99.
formatted_price = "{:.2f}".format(total_price)
# Scroll down to the price element
self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN)
self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN)
price_element = self.driver.find_element(By.XPATH, '//input[@name="price"]')
price_element.clear()
price_element.send_keys(formatted_price)
令我惊讶的是,机器人能够找到该元素,但无法清除它,并开始在之前的价格中添加新的价格。下图显示了之前的价格 162.99、184.99 和 184.99 组合到价格框中。
看起来代码很多。在不知道其余代码的情况下,这样的事情怎么样?
from browserist import Browser
# Other code goes here ...
formatted_price = "{:.2f}".format(total_price)
with Browser() as browser:
browser.open.url("https://example.com")
browser.scroll.into_view_if_not_in_viewport("//input[@name='price']") # Instead of page down twice.
browser.input.value("//input[@name='price']", formatted_price)
完全公开,我是 Browserist 包的作者。 Browserist 是 Selenium Web 驱动程序的轻量级、简洁的扩展,使浏览器自动化变得更加容易。只需使用
pip install browserist
安装软件包即可开始使用。
其他注意事项:
price_element.clear()
。browser.scroll.into_view_if_not_in_viewport(...)
行代码。从表面上看,清除价格元素的工作可能是在其完全加载/可访问之前。也许您可以添加一个等待条件,以确保在尝试与元素交互之前该元素已准备好可供访问。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
# rest of your previous code
# //
wait = WebDriverWait(self.driver, 10)
price_element = wait.until(EC.presence_of_element_located((By.XPATH, '//input[@name="price"]')))
price_element.clear()
price_element.send_keys(formatted_price)