【发布时间】:2013-09-23 08:44:52
【问题描述】:
我必须从这个来源中删除标题标签中的文本:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" lang="en">
<head>
<title>Microsoft to acquire Nokia’s devices & services business, license Nokia’s patents and mapping services</title>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9; IE=10" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta id="ctl00_WtCampaignId" name="DCSext.wt_linkid" />
</title>
我正在使用它来删除文本:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
ourUrl = opener.open("http://www.thehindubusinessline.com/industry-and-economy/info-tech/nokia-cannot-license-brand-nokia-post-microsoft-deal/article5156470.ece").read()
soup = BeautifulSoup(ourUrl)
print soup
dem = soup.findAll('p')
hea = soup.findAll('title')
此代码正确提取 p 标签,但在尝试提取标题时失败。谢谢。我只包含了一部分代码,不用担心其余部分可以正常工作。
【问题讨论】:
-
我无法重现您的问题;该页面上的 HTML 已损坏,但 BeautifulSoup 3 和 BeautifulSoup 4 的所有 3 个解析器插件都给了我正确的输出,我可以很好地提取标题。
-
您使用的是什么版本的 BeautifulSoup? 4.0系列有一些问题。此外,某些 lxml + libxml2 组合在某些 HTML 输入方面存在问题。如果您使用的是 BeautifulSoup 4,您是否安装了 lxml?
-
嗯,你得到了什么错误?或者你得到一个空列表?因为我尝试了您的代码(以及此页面),但得到了 no 错误!
标签: python beautifulsoup