1. 程式人生 > 其它 >python爬蟲實現爬取網頁主頁資訊(html程式碼)

python爬蟲實現爬取網頁主頁資訊(html程式碼)

技術標籤:pythonweb

python爬蟲實現爬取網頁主頁資訊(html程式碼)

1.爬取網站原始碼

urllib整體介紹:
urllib是一個包,收集幾個模組來處理網址
urllib.request開啟和瀏覽url中內容
urllib.error包含從 urllib.request發生的錯誤或異常
urllib.parse解析url
urllib.robotparser解析 robots.txt檔案
import urllib.request

class GetHtml(object):              #建立類,object表示主類(寫不寫都可)
    def __init__
(self, URL): #def __init__將類例項化、self:類本身 self.url = URL #為url賦值=URL def get_index(self): #定義方法 self.response = urllib.request.urlopen(self.url) return self.response.read() html = GetHtml("http://product.yesky.com/keyboard/") print(html.get_index())

執行結果:(獲取到網站原始碼)


在這裡插入圖片描述
但是在伺服器日誌資訊中會顯示訪問採用python指令碼,容易被網站管理員ban掉ip,所以需要修改其user-agent資訊

import urllib.request

class GetHtml(object):
    def __init__(self, URL, HEAD):
        self.url = URL
        self.head = HEAD

    def get_index(self):
        self.request = urllib.request.Request(self.url)   #進行請求
        self.request.
add_header("user-agent", self.head) #新增頭部資訊 self.response = urllib.request.urlopen(self.request) return self.response.read() html = GetHtml("http://product.yesky.com/keyboard/", "Mozilla/5.0 (Windows NT 8.1; Win32; x32; rv:65.0) Gecko/20100101 Firefox/65.0") #將伺服器顯示資訊進行修改 print(html.get_index())

執行結果:
在這裡插入圖片描述
伺服器端顯示結果:
·在這裡插入圖片描述
成功修改user-agent資訊,並且獲取到了網站原始碼資訊。