python - 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")
也许我需要指定列表的范围?
解决方案
我假设 的功能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
通过将其更改为任何其他方法,它可能会修复错误。
推荐阅读
- c++ - 如何调试非常慢(200 秒)的 fwrite()/ftello()/fclose()?
- android - 如果 Android 应用程序不在中国 Android 手机的堆栈中,则推送通知不起作用
- node.js - 节点如何同时处理多个请求?
- c# - 如何将此源变量绑定到现有文本框?
- c++ - 如何使用 clang 更快地编译?
- c# - 如何在 mvc html 标签中添加 vue?
- powershell - 如何在powershell中为此输出分配不同的变量?
- python - Plotly:雷达图将 theta 误认为是 int 而不是 string
- python - Python3 记忆游戏无法在表面上粘贴图像
- c++ - 我的刽子手艺术不会以正确的顺序打印