我制作了一个程序,从维基百科抓取今天的专题文章并将其打印出来:
import requests
from bs4 import BeautifulSoup
url = 'https://en.wikipedia.org/wiki/Main_Page'
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
element = soup.find('div', {'id': 'mp-tfa'})
output = element.p.get_text()
如果我添加
print(output)
,它会打印出这样的文章:“[在此处插入文章](完整文章...)”
我试图通过这样打印来删除最后的文本:
print(output.removesuffix(' (Full article...'))
但这仍然无法删除它。是我没有正确使用这个功能还是必须使用其他方法来删除它?
使用
removesuffix()
是正确的方法。但是,问题是您在调用 removesuffix()
时缺少字符串的右括号。
这是更新后的代码。
import requests
from bs4 import BeautifulSoup
url = 'https://en.wikipedia.org/wiki/Main_Page'
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
element = soup.find('div', {'id': 'mp-tfa'})
output = element.p.get_text()
cleaned_output = output.removesuffix(' (Full article...)')
print(cleaned_output)
希望这对你有一点帮助。