代码:
import socket, cchardet, ssl, time
def htmlText(url, headers=None, charset=None):
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)'} if not headers else headers
url = url if url[-1] == '/' else url + '/'
s, host = socket.socket(socket.AF_INET, socket.SOCK_STREAM), url.split('/')[2]
port, html = 80, b''
if 'https://' in url:
s, port = ssl.wrap_socket(s), 443
msg = 'GET /{0} HTTP/1.1\r\nHost: {1}\r\n{2}: {3}\r\nConnection: close\r\n\r\n'.format(url.split('/', 3)[3], host, headers.keys(), headers.values())
s.connect((host, port))
s.send(msg.encode())
while True:
rev = s.recv(1024)
if not rev: break
html += rev
charset = (cchardet.detect(html)['encoding'] if charset else 'utf-8') if not charset else charset
return html.decode(charset, errors='ignore')
if __name__ == '__main__':
start = time.time()
print(htmlText('http://www.baidu.com'))
print(time.time() - start)