簡體   English   中英

TypeError:切片索引必須為整數或無,或具有__index__方法python

[英]TypeError: slice indices must be integers or None or have an __index__ method python

為什么:

k = driver.find_elements_by_class_name("#mw-content-text > div > p:nth-child(3) > b:nth-child(1)")[0:6]

工作

Wiki的6號(又名titles.text)給出

k = driver.find_elements_by_class_name("#mw-content-text > div > p:nth-child(3) > b:nth-child(1)")[0:titles.text]

錯誤:

TypeError: slice indices must be integers or None or have an __index__ method

我該如何解決? 為什么這樣做

編碼

cd = webdriver.chrome()
cd.get('https://en.wikipedia.org/wiki/6')
titles = driver.find_elements_by_class_name("#mw-content-text > div > p:nth-child(3) > b:nth-child(1)")
for title in titles:
    print(title.text)

將其更改為int(titles.text)可以打印所有元素

根據評論,看起來titles.text的值titles.text是一個字符串(因此不能用作切片索引),並且等於1 of 6這意味着您將無法直接將其傳遞給int()進行轉換。

如果要從字符串中提取那個6 ,則可以先按of分割字符串,然后獲取最后一個元素。 然后,您需要將其轉換為整數:

max_pages = int(titles.text.split(" of ")[-1])

k = driver.find_elements_by_class_name("#mw-content-text > div > p:nth-child(3) > b:nth-child(1)")[:max_pages]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM