【发布时间】:2021-01-23 18:36:05
【问题描述】:
我正在尝试自动化我的一项手动任务。我已经编写了完整的脚本,但我被困在 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)")
非常感谢您的时间和支持。如果您需要更多信息,请告诉我。太感谢了???
【问题讨论】:
-
你为什么在循环中返回一个页面?
-
@arundeepchohan 因为如果我成功循环,我会点击每一个产品。请暂时忽略它,因为我们只专注于打印它的文本。顺便说一句,即使我删除了最后一行。循环不起作用,程序结束时没有任何错误。而且您知道结果不会打印一次。
-
@arundeepchohan 非常感谢您的帮助。我使用 css 选择器并使用 get_element_by_tag_name 打印了 img 源,但它只打印了一个结果。循环无法正常工作。我有很多性质相同的任务,我想将它们自动化。所有的概念都很清楚,但唯一的问题是在一组元素中循环。我希望你能解决这个问题。谢谢!
-
@arundeepchohan 非常感谢。我用这条线,它工作了
-
container = driver.find_elements_by_css_selector('.tile.col-x12.col-l6.col-s8.p--2')
标签: html python-3.x selenium browser-automation