一文帶你瞭解Python 四種常見基礎爬蟲方法介紹
阿新 • • 發佈:2020-12-04
一、Urllib方法
Urllib是python內建的HTTP請求庫
import urllib.request #1.定位抓取的url url='http://www.baidu.com/' #2.向目標url傳送請求 response=urllib.request.urlopen(url) #3.讀取資料 data=response.read() # print(data) #打印出來的資料有ASCII碼 print(data.decode('utf-8')) #decode將相應編碼格式的資料轉換成字串
#post請求 import urllib.parse url='http://www.iqianyue.com/mypost/' #構建上傳的data postdata=urllib.parse.urlencode({ 'name':'Jack','pass':'123456' }).encode('utf-8') #字串轉化成位元組流資料 html=urllib.request.urlopen(url,data=postdata).read() print(html)
#headers針對檢驗頭資訊的反爬機制 import urllib.request headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/58.0.3029.110 Safari/537.36' } request1=urllib.request.Request('https://www.dianping.com/',headers=headers)#Request類構建了一個完整的請求 response1=urllib.request.urlopen(request1).read() print(response1.decode('utf-8'))
#超時設定+異常處理 import urllib.request import urllib.error for i in range(20): try: response1=urllib.request.urlopen('http://www.ibeifeng.com/',timeout=0.01) print('a') except urllib.error.URLError as e: print(e) except BaseException as a: #所有異常的基類 print(a)
二、requests方法
–Requests是用python語言基於urllib編寫的,採用的是Apache2 Licensed開源協議的HTTP庫
–requests是python實現的最簡單易用的HTTP庫,建議爬蟲使用requests庫。
–預設安裝好python之後,是沒有安裝requests模組的,需要單獨通過pip安裝
import requests #get請求 r=requests.get('https://www.taobao.com/') #列印位元組流資料 # print(r.content) # print(r.content.decode('utf-8')) #轉碼 print(r.text) #列印文字資料 import chardet #自動獲取到網頁編碼,返回字典型別 print(chardet.detect(r.content))
POST請求實現模擬表單登入 import requests #構建上傳到網頁的資料 data={ 'name':'Jack','pass':'123456' } #帶登陸資料傳送請求 r=requests.post('http://www.iqianyue.com/mypost/',data=data) print(r.text) #列印請求資料 #將登入後的html儲存在本地 f=open('login.html','wb') f.write(r.content) #寫入位元組流資料 f.close()
#針對檢驗頭資訊的反爬機制headers import requests #構建headers headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/58.0.3029.110 Safari/537.36' } r=requests.get('https://www.dianping.com/',headers=headers) print(r.text) print(r.status_code) #狀態403 被攔截了(檢視狀態)
#cookies #跳過登陸,獲取資源 import requests f=open('cookie.txt','r') #開啟cookie檔案 #初始化cookies,宣告一個空字典 cookies={} #按照字元 ; 進行切割讀取,返回列表資料,然後遍歷 #split():切割函式 strip()去除字串前後空白 for line in f.read().split(';'): #split將引數設定為1,把字串切割成兩個部分 name,value=line.strip().split('=',1) #為空字典cookies新增內容 cookies[name]=value r=requests.get('http://www.baidu.com',cookies=cookies) data=r.text f1=open('baidu.html','w',encoding='utf-8') f1.write(data) f1.close()
#設定代理(網站搜尋免費代理ip) #解決網頁封IP的問題 import requests proxies={ #'協議':'ip:埠號' 'HTTP':'222.83.160.37:61205' } req=requests.get('http://www.taobao.com/',proxies=proxies) print(req.text) #設定超時 import requests from requests.exceptions import Timeout try: response = requests.get("http://www.ibeifeng.com ",timeout=0.01) print(response.status_code) except Timeout: print('訪問超時!')
三、BS4- BeautifulSoup4解析
from bs4 import BeautifulSoup html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title">The Dormouse's story</p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" rel="external nofollow" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" rel="external nofollow" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ # #建立一個BS物件 soup=BeautifulSoup(html,'html.parser') #html.parser預設解析器 print(type(soup)) # 結構化輸出 print(soup.prettify()) #1獲取標籤(只能獲取第一條對應的標籤) print(soup.p) #獲取p標籤 print(soup.a) #獲取a標籤 print(soup.title) #獲取title #2獲取標籤內容 print(soup.title.string) print(soup.a.string) print(soup.body.string) #如果標籤中有多個子標籤返回None print(soup.head.string) #如果標籤中有一個子標籤返回子標籤裡的文字 #3獲取屬性 print(soup.a.attrs) #返回字典 print(soup.a['id']) #得到指定屬性值 #4操作位元組點 print(soup.p.contents) #得到標籤下所有子節點 print(soup.p.children) #得到標籤下所有子節點的迭代物件 #5操作父節點 print(soup.p.parent) #得到標籤p的父節點其內部的所有內容 print(soup.p.parents) # 得到標籤p的父節點的迭代物件 #6操作兄弟節點(同級的節點) #next_sibling和previous_sibling分別獲取節點的下一個和上一個兄弟元素 print(soup.a.next_sibling) print(soup.a.previous_sibling) #二.搜尋文件數 #1標籤名 #查詢所有a標籤 res1=soup.find_all('a') print(res1) #獲取所有a標籤下屬性為class="sister"的標籤( #使用 class 做引數會導致語法錯誤,這裡也要用class_) print(soup.find_all('a',class_="sister")) #2正則表示式 import re #查詢所有包含d字元的標籤 res2=soup.find_all(re.compile('d+')) print(res2) #3列表 #查詢所有的title標籤和a標籤 res3=soup.find_all(['title','a']) print(res3) #4關鍵詞 #查詢屬性id='link1'的標籤 res4=soup.find_all(id='link1') print(res4) #5內容匹配 res5=soup.find_all(text='Tillie') #文字匹配 res55=soup.find_all(text=re.compile('Dormouse')) print(res55) #6巢狀選擇 print(soup.find_all('p')) #檢視所有p標籤下所有的a標籤 for i in soup.find_all('p'): print(i.find_all('a')) #三.CSS選擇器 #1根據標籤查詢物件 res6=soup.select('a') #返回列表 print(res6) #得到所有的a標籤 #2根據ID屬性查詢標籤物件(id用#) print(soup.select('#link2')) #3根據class屬性查詢標籤物件(class用.) print(soup.select('.sister')) print(soup.select('.sister')[2].get_text()) #獲取文字內容 #4屬性選擇(獲取a標籤裡=href屬性值的標籤) print(soup.select('a[href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" ]')) #5包含選擇(獲取) print(soup.select('p a#link1')) #6並列選擇 print(soup.select('a#link1,a#link2')) #7得到標籤內容 res7=soup.select('p a.sister') for i in res7: print(i.get_text())
#練習:爬取51job主頁12個職位 from bs4 import BeautifulSoup import requests url='https://www.51job.com/' headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/58.0.3029.110 Safari/537.36'} html=requests.get(url,headers=headers) data=html.content.decode('gbk') soup=BeautifulSoup(data,'html.parser') #獲取span標籤,class_="at"屬性 span=soup.find_all('span',class_="at") # for i in span: # print(i.get_text()) #select方法(CSS選擇器) span1=soup.select('span[class="at"]') for m in span1: print(m.get_text())
四、XPath語法
XPath 是一門在 XML 文件中查詢資訊的語言。
XPath 可用來在 XML 文件中對元素和屬性進行遍歷
from lxml import etree text=''' <html> <head> <title>春晚</title> </head> <body> <h1 name="title">個人簡介</h1> <div name="desc"> <p name="name">姓名:<span>岳雲鵬</span></p> <p name="addr">住址:中國 河南</p> <p name="info">代表作:五環之歌</p> </div> ''' #初始化 html=etree.HTML(text) # result=etree.tostring(html) #位元組流 # print(result.decode('utf-8')) #查詢所有的p標籤 p_x=html.xpath('//p') print(p_x) #查詢所有p標籤的文字,用text只能拿到該標籤下的文字,不包括子標籤 for i in p_x: print(i.text) #發現<span>沒有拿到 #優化,用string()拿標籤內部的所有文字 for i in p_x: print(i.xpath('string(.)')) # 查詢所有name屬性的值 attr_name=html.xpath('//@name') print(attr_name) #查詢出所有包含name屬性的標籤 attr_name1=html.xpath('//*[@name]') print(attr_name1)
到此這篇關於一文帶你瞭解Python 四種常見基礎爬蟲方法介紹的文章就介紹到這了,更多相關Python 基礎爬蟲內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!