1. 程式人生 > 其它 >Python筆記 之使用HTTP訪問網頁

Python筆記 之使用HTTP訪問網頁

技術標籤:python筆記pythonwebhttps

Python程式碼

程式碼下載

import http.client

defaultsite = 'fashion.sina.com.cn'
defaultpage = '/s/tr/2021-01-26/1845/doc-ikftssap0645087.shtml'
defaultlines = 20

def getfile():
    site = input('Enter host => ')
    if not site:
        site = defaultsite
    page = input('Enter page => '
) if not page: page = defaultpage print('Site :',site,'\n', 'Page :',page) #連線網站並請求網頁 server = http.client.HTTPConnection(site) server.putrequest('GET',page) server.putheader('ACCEPT','text/html') server.endheaders() #請求網頁內容 reply = server.getresponse(
) print('Reply :',reply) print('Code : ',reply.code,'\n', 'Reason : ',reply.reason) if reply.status != 200: print('Error sending request : Code = ',reply.status,' Reason = ',reply.reason) else: data = reply.readlines() reply.close() for line in
data[:defaultlines]: print(line.decode('utf-8')) if __name__ == '__main__': getfile()

結果

Enter host => 
Enter page => 
Site : fashion.sina.com.cn 
 Page : /s/tr/2021-01-26/1845/doc-ikftssap0645087.shtml
Reply : <http.client.HTTPResponse object at 0x0000025B6CDAF3C8>
Code :  200 
 Reason :  OK
<!DOCTYPE html>

<!-- [ published at 2021-01-26 18:45:13 ] -->





<!---->

<html>

<head>

    <meta charset="utf-8"/>

    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

	<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />

	<meta name="sudameta" content="urlpath:s/tr/; allCIDs:275,257,260,267,344,258,315,322">

    <title>“奶奶味兒”十足的毛開衫 你真的會搭嗎|穿搭|時尚|潮流_新浪時尚_新浪網</title>

<meta name="keywords" content="穿搭,時尚,潮流" />

<meta name="description" content="原標題:跟我說實話,我穿毛開衫的樣子真的很像奶奶嗎??內容來源:海報時尚&amp;nbsp;原來冬天才是真正考驗一個人穿搭技術的季節!它不像夏天,考驗的主要就是個眼光,只要T恤、裙子那件單品是好看的,那整體就是ok的。可冬天呢?裡三層外三層,簡單的" />

<meta name="tags" content="穿搭,時尚,潮流" />

	<meta property="og:type" content="news" />

<meta property="og:title" content="“奶奶味兒”十足的毛開衫 你真的會搭嗎" />

<meta property="og:description" content="“奶奶味兒”十足的毛開衫 你真的會搭嗎" />

<meta property="og:url" content="https://fashion.sina.com.cn/s/tr/2021-01-26/1845/doc-ikftssap0645087.shtml" />

<meta property="og:image" content="http://n.sinaimg.cn/fashion/transform/500/w300h200/20201202/669b-ketnnaq3352155.jpg" />


Process finished with exit code 0