【问题标题】:Error with Beautiful Soup美丽汤的错误
【发布时间】: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 &amp; 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


【解决方案1】:

您的 html 代码中有错误!你有 2 个&lt;/title&gt; 结束标签:

<!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 &amp; 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> #You already have endtag of <title>

所以固定的代码应该是这样的:

<!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 &amp; 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" />

【讨论】:

  • HTML 是从外部 URL 加载的,我怀疑 OP 可以更正页面。目标是从损坏的 HTML 源中提取标题而不修复它。
  • 是的,我添加了最后一个,因为我无法复制整个源代码。对此感到抱歉,但为什么找不到所有工作。顺便说一句,它的 bs4。
  • 你知道,试试soup.find("something")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2015-05-15
  • 1970-01-01
相关资源
最近更新 更多