拆分问题:“NoneType”对象不可调用

发布于 2025-01-09 18:37:37 字数 823 浏览 0 评论 0原文

我一直面临着分割/切片字符串的一个小问题:

import requests
from bs4 import BeautifulSoup

url = 'http://www.example.com'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
titles = soup.find_all('span', attrs='secondaryInfo')

for title in titles:
    print(title)

输出是这样的:

<span class="secondaryInfo">(1994)</span>
<span class="secondaryInfo">(1972)</span>
<span class="secondaryInfo">(1974)</span>
<span class="secondaryInfo">(2008)</span>
<span class="secondaryInfo">(1957)</span>

我想分割并获得几年,我尝试的每次分割/切片,我都会收到此错误: 我尝试了一切,例如:

year=title.split(">")
or
year = link.split('>')[1]

类型错误:“NoneType”对象不可调用

我做错了什么?我怎样才能得到“年”前。 (1974)

I have been facing a small problem with splitting/slicing string :

import requests
from bs4 import BeautifulSoup

url = 'http://www.example.com'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
titles = soup.find_all('span', attrs='secondaryInfo')

for title in titles:
    print(title)

the output is like this :

<span class="secondaryInfo">(1994)</span>
<span class="secondaryInfo">(1972)</span>
<span class="secondaryInfo">(1974)</span>
<span class="secondaryInfo">(2008)</span>
<span class="secondaryInfo">(1957)</span>

I want to split and get years , every split/slice I try , I get this error :
I tried everything for example :

year=title.split(">")
or
year = link.split('>')[1]

TypeError: 'NoneType' object is not callable

what am I doing wrong ? how can I get "Years" ex. (1974)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╭ゆ眷念 2025-01-16 18:37:38

在此代码中,titles 变量是使用 find_all() 与您的过滤器匹配的所有标签和字符串的列表。您可以在 titles 上运行 for 循环,并在每个元素上使用 getText() 来查找给定标签的文本

for title in titles:
    print(title.get_text())

如果您希望它们存储在列表中,您可以这段代码

years = [title.get_text() for title in titles]

In this code, titles variable is a list of all the tags and strings that match your filters using find_all(). You can run a for loop on titles and use getText() on each element to find the text of the given tag

for title in titles:
    print(title.get_text())

If you want them to store in a list, you can this code

years = [title.get_text() for title in titles]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文