【问题标题】:Read HEAD contents from HTML从 HTML 中读取 HEAD 内容
【发布时间】:2010-12-20 02:50:02
【问题描述】:

我需要 python 中的小脚本。需要读取 web 文件中的自定义块。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2

req = urllib2.Request('http://target.com')
response = urllib2.urlopen(req)
the_page = response.read()
print the_page # Here is all page source with html tags, but
               # i need read only section from <head> to </head>

# example the http://target.com source is:
# <html>
# <body>
# <head>
# ... need to read this section ...
# </head>
# ... page source ...
# </body>
# </html>

如何阅读自定义部分?

【问题讨论】:

  • 使用 HTML 解析器(例如 BeautifulSoup)对其进行解析。您还将获得简单 建议,例如使用正则表达式,但不要养成习惯。解析它。
  • 您需要为它解析 HTML/xhtml(如果这不是一个快速完成的脚本,可以从站点自动下载一次内容)。
  • @sukhbir 我的第二点是,使用 HTML 解析器会更加愉快(而且通常更好)。
  • 你应该知道&lt;head&gt;&lt;/head&gt;标签都是可选的。
  • @sukhbir:原因如下:stackoverflow.com/questions/1732348/…

标签: python html html-parsing


【解决方案1】:

要解析 HTML,我们使用解析器,例如 BeautifulSoup

当然你可以使用正则表达式解析它,但这是你不应该做的事情。仅仅因为它适用于某些情况并不意味着它是标准的执行方式或正确的执行方式。如果您有兴趣了解原因,请在 SO 上阅读此出色的答案 here

从 BeautifulSoup 教程开始,了解如何解析所需信息。这很容易做到。我们不会为你做,那是让你阅读和学习!

提醒您一下,您有 the_page,其中包含 HTML 数据。

>> from BeautifulSoup import BeautifulSoup
>> soup = BeautifulSoup(the_page)

现在按照教程学习如何获取head 标签中的所有内容。

【讨论】:

    【解决方案2】:
    from BeautifulSoup import BeautifulSoup
    import urllib2
    
    page = urllib2.urlopen('http://www.example.com')
    soup = BeautifulSoup(page.read())
    print soup.find('head')
    

    输出

    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Example Web Page</title>
    </head>
    

    【讨论】:

    • @Ernie 定义自定义文本是什么意思?
    • 如果我需要从 "iv="Cont" 到 "charset=utf" 读取文本,而不是从 html 标签中读取
    • @Ernie 这很不一样,你可以很容易地用正则表达式来做到这一点。 re.search(r'"iv="Cont"(.*)"charset=utf"', text).group(1)
    • @Ernie 我想你可以从你所拥有的东西中弄清楚。
    • NameError: name 're' 未定义
    【解决方案3】:

    一个解决方案是使用很棒的 python 库Beautiful Soup。它允许您非常轻松地解析 html/xml,并在文档损坏或无效时尝试提供帮助。

    【讨论】:

      猜你喜欢
      • 2010-11-02
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 2021-09-11
      • 2014-03-28
      相关资源
      最近更新 更多