如何将Python的BeautifulSoup .text转换为大写?



我正在尝试从BBC网站上的文章中抓取标题,并通过python .upper方法将其转换为大写。我使用Python的BeautifulSoup库。这是我的代码:

from bs4 import BeautifulSoup as bs
import requests
url = 'https://www.bbc.co.uk/news/world-60525350'
html = requests.get(url)
soup = bs(html.text, "html.parser")
article_box = soup.find_all('div', class_='gel-layout__item gs-u-pb+@m gel-1/3@m gel-1/4@xl gel-1/3@xxl nw-o-keyline nw-o-no-keyline@m')
for titles in article_box:
string = titles.text
upper = string.upper
print(upper,'nn')  

当我尝试这样做时,我收到的输出是:

我在这里错过了什么?我以为BeautifulSoup的。text会生成字符串。

您必须使用.upper()方法

upper = string.upper()

你需要调用一个upper方法来得到一个大写的结果。

for titles in article_box:
string = titles.text
upper = string.upper
print(upper(),'nn') 

最新更新