首页 > 解决方案 > Selenium 尝试将大小为 20 的序列分配给大小为 18 的扩展切片

问题描述

我想从有分页的网站(姓名和电话号码)中抓取数据......此代码运行良好,但是当代码达到某个页码(例如:第 9 页)时,我收到一个错误:

attempt to assign sequence of size 20 to extended slice of size 18

--- 完整代码 ---

def append_new_line(file_name, text_to_append):
    with open(file_name, "a+") as file_object:
        file_object.seek(0)
        data = file_object.read(100)
        if len(data) > 0:
            file_object.write("\n")
        file_object.write(text_to_append)

def listToString(lst1, lst2):
    result = [None]*(len(lst1)+len(lst2))
    result[::2] = lst1 #this is throwing the error (Selenium attempt to assign sequence of size 20 to extended slice of size 18)
    result[1::2] = lst2

    str1 = "" 
    
    for ele in result: 
        str1 += ele + "\n\n"
    
    return str1


while True:
    try:
        elem = driver.find_element_by_xpath("//span[@class='showLink reveal']")
        elem.click()
        name = driver.find_elements_by_xpath("//span[@itemprop='name']")
        names = [elem.get_attribute('innerHTML') for elem in name]
        mobile = driver.find_elements_by_xpath("//a[@style='display:inline']")
        mobiles = [elem.get_attribute('href') for elem in mobile]
        print(listToString(names, mobiles))
        append_new_line('datas.txt', listToString(names, mobiles))
        time.sleep(2)
        next = driver.find_element_by_css_selector("[aria-label='Next']")
        next.click()
        print(listToString(names, mobiles))
        append_new_line('datas.txt', listToString(names, mobiles))

    except NoSuchElementException:
        print("Not found")

也许我需要指定列表的范围?

标签: pythonselenium

解决方案


我假设 的功能result是从 lst1 和 lst2 生成一个交替列表。我不确定这是否可行,但您可以尝试更改创建交替列表的方式。例如,在函数listToString中,尝试将结果更改为:

result = [sub[item] for item in range(len(lst2)) for sub in [lst1, lst2]]

或者:

result = [item for pair in zip(lst1, lst2 + [0]) for item in pair]

或者:

result = sum(map(list, zip(lst1, lst2)), [])

这些方法中的每一个都做同样的事情:

esult = [None]*(len(lst1)+len(lst2))
    result[::2] = lst1
    result[1::2] = lst2

通过将其更改为任何其他方法,它可能会修复错误。


推荐阅读