Python—实训day2—爬虫案例1:访问百度贴吧
2 爬蟲案例1:訪問百度貼吧
假設我們要訪問的貼吧是:動漫吧
頭幾頁的URL地址為:
https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=0
https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=50
https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=100
https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=150
from urllib import request# 加載一個頁面 def loadPage(url):# 發起一個請求req = request.Request(url)print(req)# <urllib.request.Request object at 0x007B1370># 打開響應的對象response = request.urlopen(req)print(response)# <http.client.HTTPResponse object at 0x01F36BF0># 獲取響應的內容html = response.read()# 對獲取到的unicode編碼進行解碼content = html.decode('utf-8')return contenturl = 'https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=50' content = loadPage(url) print(content)2.1 獲取一頁的html
from urllib import request# 加載一個頁面 def loadPage(url):# 發起一個請求req = request.Request(url)print(req)# <urllib.request.Request object at 0x007B1370># 打開響應的對象response = request.urlopen(req)print(response)# <http.client.HTTPResponse object at 0x01F36BF0># 獲取響應的內容html = response.read()# 對獲取到的unicode編碼進行解碼content = html.decode('utf-8')return contenturl = 'https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=50' content = loadPage(url) print(content)2.2 把網頁的內容保存到本地html文件
# 把下載內容保存到本地文件 def writePage(html, filename):print('正在保存到:', filename)f = open(filename, 'w', encoding='utf8')f.write(html)f.close()url = 'https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&pn=50' content = loadPage(url) filename = 'tieba.html' writePage(content, filename)2.3 設置起始頁和終止頁
# 設置起始頁和終止頁 def tiebaSpider(url, beginPage, endPage):for page in range(beginPage, endPage+1):pn = 50*(page-1)fullurl = url + str(pn)content = loadPage(fullurl)filename = '第' + str(page) + '頁.html'writePage(content, filename)url = 'https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&pn=' tiebaSpider(url, 1, 4)2.4 用戶輸入參數
from urllib import request, parse # 設置起始頁和終止頁 if __name__ == '__main__':kw = input('請輸入要爬取的貼吧:')beginPage = int(input('請輸入起始頁:')) # input()返回的內容是字符串 需要通過int()強制轉換為整數endPage = int(input('請輸入終止頁:'))key = parse.urlencode({'kw':kw})print(key)url = 'https://tieba.baidu.com/f?' + keytiebaSpider(url, beginPage, endPage)3 Fiddler抓包工具
3.1 安裝
安裝過程略
3.2 配置
通過 Tool —— Options打開選項
切換到 HTTPS 標簽,選上下面的選項
然后點擊Actions按鈕,在彈出框選擇 Trust Root Certificate
如果彈出如下對話框,選擇Yes
配置完成后,重啟Fiddler,重啟瀏覽器
打開百度貼吧,留意User-Agent的信息
運行爬蟲程序,再留意一下User-Agent的信息
有可能運行了Fiddler,再運行爬蟲程序的時候,會出現認證失敗的問題
SSL:CERTIFICATE ERROR
此時,需要添加未經過驗證的上下文的代碼
from urllib import request, parse import ssl # 加載一個頁面 def loadPage(url):# 發起一個請求req = request.Request(url)#print(req) # <urllib.request.Request object at 0x007B1370># 創建未經過驗證的上下文的代碼context = ssl._create_unverified_context()# 打開響應的對象response = request.urlopen(req, context=context)#print(response) # <http.client.HTTPResponse object at 0x01F36BF0># 獲取響應的內容html = response.read()# 對獲取到的unicode編碼進行解碼content = html.decode('utf-8')return content3.3 反爬蟲與防反爬蟲
爬蟲 —— 反爬蟲 —— 反反爬蟲
關于反爬蟲的博客:
https://segmentfault.com/a/1190000005840672
3.3.1 改變User-Agent
添加請求頭,修改User-Agent
通過抓包工具捕獲正確的瀏覽器訪問服務器的User-Agent
?
把請求頭添加到 headers 參數中
# 加載一個頁面 def loadPage(url):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'}# 發起一個請求req = request.Request(url, headers = headers)#print(req) # <urllib.request.Request object at 0x007B1370># 創建未經過驗證的上下文的代碼context = ssl._create_unverified_context()# 打開響應的對象response = request.urlopen(req, context=context)#print(response) # <http.client.HTTPResponse object at 0x01F36BF0># 獲取響應的內容html = response.read()# 對獲取到的unicode編碼進行解碼content = html.decode('utf-8')return content3.3.2 隨機選擇User-Agent
考慮更換使用不同的User-Agent
from urllib import request, parse import ssl import random # 常用User-Agent列表 ua_list = ['User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50','Mozilla/5.0 (Windows; U; Windows NT 6.1; ) AppleWebKit/534.12 (KHTML, like Gecko) Maxthon/3.0 Safari/534.12','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1 QQBrowser/6.9.11079.201','Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)', ] # 加載一個頁面 def loadPage(url):# 在ua_list列表中隨機選擇一個UserAgentuserAgent = random.choice(ua_list)headers = {'User-Agent': userAgent}# 發起一個請求req = request.Request(url, headers = headers)#print(req) # <urllib.request.Request object at 0x007B1370># 創建未經過驗證的上下文的代碼context = ssl._create_unverified_context()# 打開響應的對象response = request.urlopen(req, context=context)#print(response) # <http.client.HTTPResponse object at 0x01F36BF0># 獲取響應的內容html = response.read()# 對獲取到的unicode編碼進行解碼content = html.decode('utf-8')return content4 發送POST請求
4.1 GET請求和POST請求
當想要向服務器發送請求的時候,可以考慮附加請求的參數
GET請求:把參數直接附加到URL地址的后面
https://tieba.baidu.com/f?kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=50
這里要訪問的URL地址為:https://tieba.baidu.com/f
添加了參數:kw=%E5%8A%A8%E6%BC%AB&ie=utf-8&pn=50
要訪問的貼吧:動漫吧
瀏覽器編碼格式:UTF-8
開始帖子的ID:50
POST請求:則把參數附加到請求體中。明眼上看不到
POST請求一般會通過表單的形式附加
<form target="xxx.php" method="post">姓名:<input type="text"/>密碼:<input type="password"/><input type="submit"/> </form>如果要提交數據給后面,使用POST請求。常用于表單的提交
4.2 FireFox的poster插件
注意:安裝FireFox的時候,不要安裝過于高級的版本。因為高的版本對poster不兼容,一般安裝50以下的版本才行
注意:FireFox第一次運行的時候,會自動更新到最新版本,所以安裝完成后,先把更新的功能去掉
打開FireFox的安裝目錄 C:\Program Files (x86)\Mozilla Firefox
把Update開頭的文件刪除
此時,啟動FireFox,此時就不會更新了
把Fiddler關閉
在FireFox中訪問 about:config
修改xpinstall.signatures.required(大概是倒數第4個)
把該值改為false
把poster-3.1.0-fx.xpi直接拖動到FireFox中
點擊安裝
安裝完成后,重啟FireFox。
按ALT鍵彈出菜單項,通過工具菜單選擇Poster
就可以打開Poster插件了
假設在172.168.10.183服務器上已經搭建好testpost.php程序,通過如下方式即可訪問GET請求
http://172.16.10.183/testpost.php?name=zhangsan&age=23&sex=male
如果要發送POST請求,首先在URL地址上輸入
點擊Parameters標簽
回到Content to Send標簽。點擊Body from Parameters,則參數就傳遞過來了
點擊POST按鈕,發送POST請求
總結
以上是生活随笔為你收集整理的Python—实训day2—爬虫案例1:访问百度贴吧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个人幸运的前提,是他有能力改变自己
- 下一篇: 养成这8个好习惯 开车会很安全的