我具有以下要素:<a class="text-name username ng-binding" ng-href="https://www.roblox.com/users/18734213/profile" ng-bind="resaleRecord.seller.name" href="https://www.roblox.com/users/18734213/profile">RobotronicDude</a>
im尝试使用漂亮的汤打印第一个ng-href 但它说:
Traceback (most recent call last):
File "C:\Users\Maxva\Desktop\Python Projects\LimSniepr\LimSniper.py", line 24, in <module>
ta = soup.findAll('a', {'class': 'text-name username ng-binding'})[0]['ng-href']
IndexError: list index out of range
我尝试过的代码:
id = input("Enter a id to snipe: ")
url = f'https://www.roblox.com/catalog/{id}/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
ta = soup.findAll('a', {'class': 'text-name username ng-binding'})[0]['ng-href']
print(ta)```
答案 0 :(得分:0)
您应该检查为什么打印解析后得到的列表会发生这种情况。以下代码可以正常工作:
from bs4 import BeautifulSoup
s = """\
<a class="text-name username ng-binding" ng-href="https://www.roblox.com/users/18734213/profile" ng-bind="resaleRecord.seller.name" href="https://www.roblox.com/users/18734213/profile">RobotronicDude</a>
"""
soup = BeautifulSoup(s, features="lxml")
for item in soup.find_all('a', {'class': 'text-name username ng-binding'}):
print(item['ng-href'])
还有可能是您的网址不正确,所以我强烈建议使用soup.prettify
进行检查