TypeError:不可用的类型:' slice'使用美丽的小组
我希望此代码在for循环的第一个元素之外打印出所有内容。但是我有一个切片错误。
from bs4 import BeautifulSoup
import requests
from openpyxl import Workbook
f = open(r'C:\Users\anilo\Documents\Anilo\Projekte\Python\Verben\Konjugation des Verbs machen _ alle Zeitformen _ Duden.html', 'r', encoding='utf-8')
html_doc = f.read()
soup = BeautifulSoup(html_doc, 'html.parser')
uls = soup.find_all('ul', class_='accordion__list content-column')[1]
for li in uls:
konjugation = li.text
konjugation_neu = konjugation.replace('1', '')
print(konjugation_neu)
输出:
Präteritum
machte (mich/mir)
machtest (dich/dir)
machte (sich)
machten (uns)
machtet (euch)
machten (sich)
li in uls中的LI [1:]:
导致错误typeerror:不可用的类型:'slice'
任何人都知道如何在不编辑的情况下执行技巧我的大部分代码,因为我需要这个面试项目。
提前致谢。
I want this code printing out everything except the first element of the for loop. But I get an slice error.
from bs4 import BeautifulSoup
import requests
from openpyxl import Workbook
f = open(r'C:\Users\anilo\Documents\Anilo\Projekte\Python\Verben\Konjugation des Verbs machen _ alle Zeitformen _ Duden.html', 'r', encoding='utf-8')
html_doc = f.read()
soup = BeautifulSoup(html_doc, 'html.parser')
uls = soup.find_all('ul', class_='accordion__list content-column')[1]
for li in uls:
konjugation = li.text
konjugation_neu = konjugation.replace('1', '')
print(konjugation_neu)
Output:
Präteritum
machte (mich/mir)
machtest (dich/dir)
machte (sich)
machten (uns)
machtet (euch)
machten (sich)
The line for li in uls[1:]:
results into an error TypeError: unhashable type: 'slice'
Does anybody know how to do the trick without editing too much of my code, because I need this for my interview project.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您从
resultset
中选择一个元素:因此,您无法将其切成薄片 - 删除元素选择并添加您的切片:
注: 您的切片将迭代所有UL,除非第一个 - 如果应该选择第一个切片看起来像
[:1]
示例,
以真正获取每个
&lt ; li>
在您的< ul>
切片时,您必须添加额外的迭代:输出
Issue here is that you pick a single element from your
ResultSet
with:So you wont be able to slice it - Remove the element picking and add your slice like this:
Note: Your slicing will iterate all ul except for the first - in case it should only pick the first slice would look like
[:1]
Example
To really get each
<li>
in your<ul>
while slicing it you have to add an extra iteration:Output