如何在Python中获取特定的行

2024-09-29 11:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python写一行,但是我被卡住了。在

这是我的代码:

import urllib2
response = urllib2.urlopen('http://pythonforbeginners.com/')
info = response.info()
html = response.read()
# do something
response.close()  # best practice to close the file

if "x" in str(info):
print str(info)

raw_input()

我只是想得到一条线来显示服务器的类型。在


Tags: 代码importinfocomhttpclosereadresponse
2条回答

我猜你的行是指http头中的一行。 您可以通过以下代码获取http头:

import urllib2
response = urllib2.urlopen('http://pythonforbeginners.com/')
info = response.info()
html = response.read()
# do something
response.close()  # best practice to close the file
# this is how to process the http header
for key in info :
    print key, info[key] 

raw_input()

或者,您可以将信息转换为字符串并按\r\n拆分(http头由\r\n分隔),如下所示

^{pr2}$

您真的需要将info视为字符串吗?如果没有,这应该很有效:

for h in info.headers:
  if h.startswith('Server'):
    print h

相关问题 更多 >