首页 > 解决方案 > Selenium Python 中的一组元素中的 For 循环

问题描述

我正在尝试自动化我的一项手动任务。我已经编写了完整的脚本,但我被困在 For Loop 无法正常工作的地方。

这是我想做的事情:

这是我想要循环并执行一些操作的一组卡片。出于测试目的,我只是想打印所有产品的标题。 这是我想要循环并执行一些操作的一组卡片

这是之前附上的图片的主要代码。class = 'm--t--1' 是包含所有这些产品的主要元素。 这是之前附上的图片的主要代码。

以下是单个产品的代码。
单品代码

现在,这是我编写的代码。注意:这不是完整的脚本。我刚刚编写了脚本中遇到问题的部分。

#Logging into the website with credentials and saved cookies!
driver.get("https://poshmark.com/login")
time.sleep(5)
driver.maximize_window()
time.sleep(5)
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

time.sleep(5)
driver.find_element_by_xpath('//*[@id="login_form_username_email"]').send_keys('email hidden')
time.sleep(5)
driver.find_element_by_xpath('//*[@id="login_form_password"]').send_keys('password hidden')
time.sleep(5)
driver.find_element_by_xpath('//*[@id="email-login-form"]/div[4]/button').click()

#Navigating to the closet where these products can be found.
driver.find_element_by_xpath('//*[@id="app"]/header/nav[1]/div/ul/li[5]/div/div[1]').click()
driver.find_element_by_xpath('//*[@id="app"]/header/nav[1]/div/ul/li[5]/div/div[2]/ul/li[1]/a').click()

container_of_products = driver.find_elements_by_class_name('tile col-x12 col-l6 col-s8 p--2')

for item in container_of_products:
    listing = item.find_element_by_tag_name('a')
    print(listing.text)
    driver.execute_script("window.history.go(-1)")

我非常感谢您的时间和支持。如果您需要更多信息,请告诉我。太感谢了

标签: htmlpython-3.xseleniumbrowser-automation

解决方案


tile col-x12 col-l6 col-s8 p--2 是一个复合类名,它不会那样工作。使用 CSS 选择器和 .tile.col-x12.col-l6.col-s8.p--2

container = driver.find_elements_by_css_selector('.tile.col-x12.col-l6.col-s8.p--2')

推荐阅读