【问题标题】:Why is the zip() function not returning expected results in list using Python/Selenium?为什么 zip() 函数没有在使用 Python/Selenium 的列表中返回预期结果?
【发布时间】:2018-10-30 16:04:31
【问题描述】:

我有一个使用 Python/Selenium 的代码块,它应该遍历网页上的各种项目并显示该项目是否可用,如果可用,则显示该项目的名称和颜色并提供页面的链接。该代码在售罄的商品上按预期工作,但是当它到达第一个可用商品时,python 只返回“可用”并提供页面上最后一个商品的名称/url,而不是预期的商品。代码块:

shirts = driver.find_elements_by_xpath("""//*[@id='container']/article/div/h1/a""")
colors = driver.find_elements_by_xpath("""//*[@id='container']/article/div/p/a""")
articles = driver.find_elements_by_tag_name('article')
for article in articles:
    ActionChains(driver).move_to_element(article).perform()
    if article.find_element_by_tag_name('a').text == "sold out":
        print("sold out")
    elif article.find_element_by_tag_name('a').text == "":
    ActionChains(driver).move_to_element(article).perform()
        print("available")
    for shirt, color in zip(shirts, colors):
        shirt_text = shirt.text
        color_text = color.text
    print shirt_text, color_text
    link = article.find_element_by_xpath('div/a').get_attribute('href')
    print(link)

这是上面代码返回的 sn-p: (应显示的预期项目是 Plaza Sunglasses Magenta)

sold out
sold out
available
Supreme®/Hanes® Crew Socks (4 Pack) White
https://www.supremenewyork.com/shop/accessories/zf83g0dx4/hijz30rq8
sold out
sold out
sold out
sold out
sold out
sold out

以及我正在抓取的页面链接: http://www.supremenewyork.com/shop/all/accessories

我的脚本设置不正确还是我完全遗漏了什么?

【问题讨论】:

    标签: python list selenium web-scraping zip


    【解决方案1】:

    它只打印最后一个产品名称,因为您的shirts 列表包含整个页面上的所有产品名称,并且shirt_text 设置为该列表中的最后一项。

    相反,将名称和颜色的查询移到文章循环中:

    for article in articles:
        if article.find_element_by_tag_name('a').text == 'sold out':
            print('sold out')
        else:
            print('available')
            [...]
            nameLink = article.find_element_by_xpath('div/h1/a')
            colorLink = article.find_element_by_xpath('div/p/a')
            [...]
    

    【讨论】:

    • 将查询移至已售完商品的顶部文章循环还是底部循环?
    • 只有在项目可用时才能提取名称。
    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 2021-01-27
    • 2023-03-17
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多