python 实现http请求,获取新浪界面(socket,while循环)


import socket,time
#coding:UTF-8
#发送的http包头
header_send='GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n'
i=0
#请求次数
num=1
#请求间隔
tinktime=1
#目的地址
ip_dst='www.sina.com.cn'
#目的端口
port_dst=80
while i<num:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip_dst,port_dst))
s.send(header_send)
buffer = []
while True:
    # 每次最多接收1k字节:
    d = s.recv(1024)
    if d:
        buffer.append(d)
    else:
        break
data = b''.join(buffer)
s.close()
header, html = data.split(b'\r\n\r\n', 1)
result='200 OK' in header
if result:
print 'SUCCESS'
print(header.decode('utf-8'))
#print html
# 把接收的数据写入文件:
#with open('D:\python\pythoncode\lfxx\wangzhan\web\sina.html', 'wb') as f:
     #f.write(html)
else:
print 'web error'
i=i+1
time.sleep(tinktime)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM