我正在尝试获取大量状态信息,这些信息在网站中编码,主要在“ head >”元素内。
我知道我可以使用wget
or curl
或 python 获取整个页面。但我不想给服务器带来太多不必要的压力(页面本身相当大/复杂)。
有没有什么方法可以只获取头元素?
我认为除了检查 html 标头之外,代理服务器还执行其他操作。
只是为了澄清:我不搜索 html-headers,只搜索 html-<head>
.
不可能只加载之间的数据<head>
标签,因为服务器在发送请求的页面之前必须解析该页面。
一个可能的解决方案是读取几个字节,直到</head>
找到标签。
以下内容如下n
来自源的字节并检查字符串是否</head>
已经包括了。如果是这样,字节将转换为string
并修剪以使结果包含标签<head>
and </head>
以及它们之间的数据。否则继续读取n
字节直到</head>
被发现。
import urllib.request
def get_head_tag_data(url, n=512):
"""Read n bytes form source until '</head> is included. Trim result to
'<head> ... </head>' and return it as string."""
# open resource
with urllib.request.urlopen(url) as site:
# read n bytes until `buff` includes "</head>"
data = b''
i = 1
while True:
buff = site.read(n)
data += buff
if b'</head>' in buff:
break
elif buff == b'':
raise AttributeError('Not head-tag found.')
i += 1
print('{} bytes read'.format(n*i))
# cast to string
data = str(data)
# detect tag position
start_tag = data.find('<head>')
end_tag = data.find('</head>') + 7
return data[start_tag:end_tag]
tag_data = get_head_tag_data('https://stackoverflow.com', n=256)
请注意,此函数不会检查可能的错误,例如,如果没有</head>
tag.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)