Skip to main content
 首页 » 编程设计

Python 和 BeautifulSoup URL 解析

2024年10月24日10kerrycode

我有以下代码,我用它来尝试从 redsox 新闻中获取标题和描述。我让它工作,但有一个小细节。它显示标签。我怎样才能消除它们?

import urllib2 
from BeautifulSoup import BeautifulSoup 
# or if you're using BeautifulSoup4: 
# from bs4 import BeautifulSoup 
 
soup = BeautifulSoup(urllib2.urlopen('http://partner.mlb.com/partnerxml/gen/news/rss/bos.xml').read()) 
 
title = soup.find('item').title 
desc = soup.find('item').description 
 
print "Title: %s " % (title) 
print "Summary: %s " % (desc) 

是这样显示的

Title: <title>Shaw or Panda? Hot corner duel heats up</title>  
Summary: <description>With two weeks until Opening Day, the hottest topic in Red Sox camp is the competition at the hot corner between incumbent Pablo Sandoval and the emerging Travis Shaw.</description>  
>>>  

请您参考如下方法:

尝试:

print "Title: %s " % (title.text) 
print "Summary: %s " % (desc.text) 

您可以使用 BeautifulSoup 做得更好,但这是让它发挥作用的快速方法。