【问题标题】:Python Selenium loop through pages and input values to a sitePython Selenium 循环遍历页面并将值输入到站点
【发布时间】:2021-10-24 05:40:25
【问题描述】:

我希望您能帮助我解决我的问题,我想将我在 excel 文件中的一些 SKU(库存单位)给出的值输入到 b2b 网站以进行自动订购。 b2b 网站有 5 页产品,我想在此过程中浏览这些产品。例如excel文件的结构如下:

我想让程序在b2b网站的第一页搜索第一个SKU,如果找到,输入数量,如果没有,转到下一页,从再次顶部,输入值等,直到它结束的第 5 页。到目前为止,我提供了以下代码(实际上是错误的部分):


def loop():
    for y in range(13,100):
        if sheet.cell(row=y,column=1).value is None:
            y+=1
        else:
            x=sheet.cell(row=y,column=4).value
            z=sheet.cell(row=y,column=1).value
            p=sheet.cell(row=2,column=10).value
            print(p)
            element = WebDriverWait(driver, 1).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@id="%s"]'%z)))
            
            try:
                yo=driver.find_element_by_xpath('//*[@id="%s"]'%z).send_keys(x)
                print(yo)
                y+=1
                print(y)
            except:
                for pa in range(1,p):
                    driver.find_elements_by_xpath('//*[@id="products_table_next"]')

显然代码不起作用。它输入第一页的值并在那里结束。我试着稍微调整一下,但我没有运气。我不是专业的开发人员,所以我很感激任何帮助!

【问题讨论】:

  • 请将您的问题缩小到您的代码似乎不起作用的确切部分。
  • @HammadAli 有问题的代码部分是 def 循环。我认为我必须留下整个代码以供参考

标签: python selenium web-scraping xpath webdriver


【解决方案1】:

显然我找到了答案。代码使用以下代码循环浏览页面:

def loop2():
 for y in range(13,200):
            if sheet.cell(row=y,column=1).value is None:
                y+=1
                print("changed y due to blank")
            else:
                x=sheet.cell(row=y,column=4).value
                z=sheet.cell(row=y,column=1).value
                try:
                    driver.find_element_by_xpath('//*[@id="%s"]'%z).send_keys(x)
                    sheet.cell(row=y,column=1).value=""
                    wb.save('novartis.xlsx')
                    y+=1
                except:
                    continue
                
for pa in range(1,p+1):
    loop2()
    driver.find_element_by_xpath('//*[@id="products_table_next"]').click()
    pa+=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多