【发布时间】: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 解析器会更加愉快(而且通常更好)。
-
你应该知道
<head>和</head>标签都是可选的。 -
@sukhbir:原因如下:stackoverflow.com/questions/1732348/…
标签: python html html-parsing