手动爬虫之流程笔记1(python3)
生活随笔
收集整理的這篇文章主要介紹了
手动爬虫之流程笔记1(python3)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、引入拓展庫
由于剛剛起步學習爬蟲,故從urllib庫開始
首先引入urllib,這里主要用到urllib中request類
import urllib.request as ur?
二、設置全局參數
我把它分為三個變量:代理服務器IP、目標網址、存放路徑。
# 代理服務器的地址 proxy_add = "110.183.238.145:811" # 獲取目標網址 url = "https://www.baidu.com" # 設置目標文檔(路徑+文件名【包括后綴】) aim_file = "E:/workspace/PyCharm/codeSpace/books/python_web_crawler_book/chapter4/demo2/1.html"??
三、將爬蟲模擬成瀏覽器訪問頁面
由于urlopen不支持一些HTTP的高級功能,所以要想達到預期的訪問效果,有兩種方式。
一是使用build_opener()修改報頭,二是使用add_header()添加報頭。本人更加傾向于第二種,使用方法如下
# 添加報頭 req = ur.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0')?
四、設置服務器代理
# 設置代理 proxy = ur.ProxyHandler({'http': proxy_add}) opener = ur.build_opener(proxy, ur.HTTPHandler) ur.install_opener(opener)?
五、爬行頁面并信息存檔
# 讀取數據 info = ur.urlopen(req).read() fh = open(aim_file, "wb") # 信息轉檔 fh.write(info) # 關閉文件 fh.close()?
六、源代碼:
1 import urllib.request as ur 2 3 # 代理服務器的地址 4 proxy_add = "110.183.238.145:811" 5 # 獲取目標網址 6 url = "https://www.baidu.com" 7 # 設置目標文檔(路徑+文件名【包括后綴】) 8 aim_file = "E:/workspace/PyCharm/codeSpace/books/python_web_crawler_book/chapter4/demo2/1.html" 9 10 # 添加報頭 11 req = ur.Request(url) 12 req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0') 13 14 # 設置代理 15 proxy = ur.ProxyHandler({'http': proxy_add}) 16 opener = ur.build_opener(proxy, ur.HTTPHandler) 17 ur.install_opener(opener) 18 19 # 讀取數據 20 data = ur.urlopen(req).read() 21 # 文件指向 22 fh = open(aim_file, "wb") 23 # 信息轉檔 24 fh.write(data) 25 # 關閉文件 26 fh.close()?
?
轉載于:https://www.cnblogs.com/xiaomingzaixian/p/7107386.html
總結
以上是生活随笔為你收集整理的手动爬虫之流程笔记1(python3)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows XP时代终结:假设你还在
- 下一篇: python exception的传递