首页 > 解决方案 > Python - 试图将hrefs放入可用列表中

问题描述

我正在 Python (noobie) 中使用 libary BeautifulSoup,并且试图将 href 的元素放入我可以保存和使用的字符串列表中。但我只能从 for 循环中获得列表中的一个。有人可以帮忙吗?我不拒绝解释:)

a_counter = 0
for link in soup.find_all('a', class_="MuiGrid-root", href=True):
        lst = [range(a_counter)]
        lst[0] = link.get('href')
        print(lst)
        a_counter += 1 #not in use becaouse lst[a_counter] = link.get('href') out of range error.

我尝试的是在列表中添加一些随机元素,错误不会出现,但它似乎不起作用。

提前致谢

标签: pythonlistbeautifulsoup

解决方案


我认为您正在覆盖列表中的相同元素,因此只能获得一个 url。而不是这样做:lst[0] = link.get('href')您可以使用lst.append(link.get('href'))将链接附加到您的列表。


推荐阅读