【问题标题】:Extract title from url with python使用python从url中提取标题
【发布时间】:2019-09-12 22:29:37
【问题描述】:

我想使用urllib 从下面的 html 文档中提取标题。我在下面提供了开始部分:

html_doc = """
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
      "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
  <title>Three Little Pigs</title>
  <meta name="generator" content="Amaya, see http://www.w3.org/Amaya/">
</head>

<body>

我在urllib.request 中使用了urlopen,但似乎html 文档中的url 类型不允许我提取任何内容。

我试过了:

from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_title():
    soup = urlopen(html_doc)
    print(soup.title.string)
get_title()

我得到了结果:

ValueError: unknown url type: '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n      "http://www.w3.org/TR/html4/loose.dtd">\n<html>\n<head>\n  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">\n  <title>Three Little Pigs</title>\n  <meta name="generator" content="Amaya, see http://www.w3.org/Amaya/">\n</head>\n\n<body'

谁能帮忙解决这个问题?

【问题讨论】:

  • 你能发布整个错误吗?

标签: python beautifulsoup urllib


【解决方案1】:

html_doc不是URL,它是真正的源代码字符串,你可以使用BeautifulSouphtml.parser来解析它,然后从中提取标题:

from bs4 import BeautifulSoup

def get_title():
    soup = BeautifulSoup(html_doc, 'html.parser')
    print(soup.title.string)

get_title()

输出:

Three Little Pigs

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2015-01-07
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多