Bs4和Python请求

2024-09-28 14:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图制作一个pokedex(https://replit.com/@Yoplayer1py/Gui-Pokedex),我想从https://www.pokemon.com/us/pokedex/{__pokename__}这里得到口袋妖怪的描述pokename表示口袋妖怪的名称。例如:https://www.pokemon.com/us/pokedex/unown

有一个标记包含描述,p标记的类是:version xactive

当我打印描述时,我什么也得不到,或者有时一个也得不到

代码如下:

import requests
from bs4 import BeautifulSoup

# Assign URL
url = "https://www.pokemon.com/us/pokedex/"+text_id_name.get(1.0, "end-1c")
    
# Fetch raw HTML content
html_content = requests.get(url).text
    
# Now that the content is ready, iterate 
# through the content using BeautifulSoup:
soup = BeautifulSoup(html_content, "html.parser")
    
# similarly to get all the occurences of a given tag
print(soup.find('p', attrs={'class': 'version-xactive'}).text)

text_id_name.get(1.0, "end-1c")来自tkinter文本输入

它表明:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "main.py", line 57, in load_pokemon
    print(soup.find('p', attrs={'class': 'version-xactive'}).text)
AttributeError: 'NoneType' object has no attribute 'text'

提前谢谢


Tags: thetexthttpscomgetversionhtmlwww
2条回答

你可能应该把你的电话分开,这样你就可以进行安全检查和类型检查

替换

print(soup.find('p', attrs={'class': 'version-xactive'}).text)

tags = soup.find('p', attrs={'class': 'version-xactive'})
print("Tags:", tags)
if(type(tags) != NoneType):
    print(tags.text)

这至少会给你更多的信息。它仍可能在tags.text上中断。如果有,请将print("Tags:", tags)的打印输出向上,这样我们就可以看到数据的样子

看起来描述的类multiple是version-x active(至少对于Unown)。这就是为什么soup.find('p', attrs={'class': 'version-xactive'}找不到元素,从而返回None(因此得到错误)

添加空间将解决您的问题:print(soup.find('p', attrs={'class': 'version-xactive'}).text)。注意:如果有多个p元素具有相同的类,那么find方法可能不会返回所需的元素

添加空检查也将防止发生错误:

description = soup.find('p', attrs={'class': 'version-x active'})
if description:
    print(desription.text)

相关问题 更多 >

    热门问题