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