Python 美丽的汤印刷

Python 美丽的汤印刷,python,beautifulsoup,Python,Beautifulsoup,我有以下元素: 我正在尝试用漂亮的汤打印第一个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'})

我有以下元素:

我正在尝试用漂亮的汤打印第一个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

您应该通过打印解析后得到的列表来检查为什么会发生这种情况。以下代码可以正常工作:

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'])
从bs4导入美化组
s=”“”\
"""
汤=美汤(s,features=“lxml”)
对于汤中的项目。查找所有('a',{'class':'text name username ng binding'}):
打印(项目['ng-href'])

也可能是因为你没有正确的url,所以我强烈建议你使用
soup。如果你只把类作为“用户名”来使用,那么请美化
来检查这个??它仍然抛出错误吗?我的意思是,像so-
soup.findAll('a',{'class':'username'})[0]['ng-href']
是的,它仍然抛出错误,很可能是您请求的页面上的动态内容-意味着从javascript加载页面内容。在这种情况下,您可能必须尝试
请求html
库,而不是
请求
库。库参考-如果您尝试
打印(len(soup.findAll('a',{'class':'text name username ng binding'}))
,您会得到什么?
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'])