一、前導庫用法
Json庫
bs4、lxml主要針對html語言編寫的代碼,有時請求的內容返回Json代碼,就需要用到Json庫( Java Script Object Notation)。
Json庫常用的方法是json.loads,用於解碼 JSON 數據。該函數返回 Python 字段的數據類型。
import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = json.loads(jsonData)
print text
樣板:
#獲取智聯招聘職位信息
import requests
from lxml import etree
import json
def get_urls():
url = 'https://fe-api.zhaopin.com/c/i/sou?start=0&pageSize=90&cityId=765&salary=0,0&workExperience=-1&education=-1&companyType=-1&employmentType=-1&jobWelfareTag=-1&kw=pcb&kt=3&=0&_v=0.94714929&x-zp-page-request-id=ab2041e0e0b84d7'
rec = requests.get(url=url)
if rec.status_code == 200:
j = json.loads(rec.text) #解析之後的類型爲字典類型
results = j.get('data').get('results')
for i in results:
jobname=i.get('jobName')#獲取職位名稱
print(jobname)
get_urls()
lxml庫
是python的一個解析庫,支持HTML和XML的解析,支持XPath解析方式,而且解析效率非常高。
1、使用 lxml 的 etree 庫,可以自動修正 HTML 代碼。
from lxml import etree # 導入 lxml etree 庫
html = etree.HTML(text) # 獲取 html 內容 元素
result = etree.tostring(html)# 將內容元素轉換爲字符串
print(result.decode("utf-8"))# utf-8 格式輸出
2、利用 parse 方法來讀取文件
from lxml import etree
html = etree.parse('text.xml')# text.xml 是一個 xml 文件,並在當前文件同目錄下
# pretty_print: 優化輸出
result = etree.tostring(html, pretty_print=True)
print(result)
樣板:
#獲取網站的標題
import requests
from lxml import etree#導入相關的庫
url = 'https://www.ftms.com.cn/footernav/tendernotice'
data = requests.get(url) #獲取 url 網頁源碼
data.encoding="utf-8"
html = etree.HTML(data.text)#將網頁源碼轉換爲 XPath 可以解析的格式
title = html.xpath('/html/head/title/text()') #獲取title
print(title)
requests 庫
1、get方法的常用請求參數:url,headers,proxies
rec = requests.get(url) #url爲請求的網址,必填參數
rec = requests.get(url,headers,proxies)#headers,proxies兩個參數爲可選,是反爬蟲用
2、請求後生成rec的 Response 對象,該對象的主要方法有:
* rec.url:返回請求網站的 URL
* rec.status_code:返回響應的狀態碼,正常相應爲200,
* rec.content:返回 bytes 類型的響應體
* rec.text:返回 str 類型的響應體,相當於 response.content.decode('utf-8')
* rec.json():返回 dict 類型的響應體,相當於 json.loads(response.text)
注意:.text 和 .content 的區別:
(1)text 返回的是unicode 型的數據,一般是在網頁的header中定義的編碼形式。content返回的是bytes,二進制型的數據。
(2)一般來說 .text直接用比較方便,返回的是字符串,但是有時候會解析不正常導致,返回的是一堆亂碼這時用 .content.decode(‘utf-8’) 就可以使其顯示正常。
(3)提取文本用text,提取圖片、文件用content。
骨幹樣板:
import requests
url = 'http://www.yhjbox.com'
data = requests.get(url) #請求網頁
完善點樣板(加上headers、proxies參數):
import requests
url="http://www.yhjbox.com"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"
"Cookie": "dafbaidaodf"}#設置請求網頁時候的請求頭
proxies = {"http": "http://1.197.203.57:9999"} #設置代理ip
rec = requests.get(url=url,headers=headers,proxies=proxies)
print(data.text)#打印網頁源代碼,字符串,正常解析
print(data.content)#打印網頁源代碼,二進制形式
二、四大選擇器用法 / 對比
結論:
(1)上手難易度:bs4、xpath比較容易上手但是功能有限,正則比較晦澀難懂但是功能超級強大。
(2)爬蟲個人目的:
(2-1)如果你的爬蟲瓶頸是下載網頁,而不是抽取數據,那麼用較慢的方法(如BeautifulSoup) 也不成問題。
(2-2)如果只需抓取少量數據,並且想要避免額外依賴的話,那麼正則表達式可能更加適合。
(2-3)but,通常lxml是抓取數據的最好選擇,因爲該方法既快速又健壯,而正則和bs只在某些特定場景下有用。
(3)效率 / 同一工作耗時:首選正則表達式,如果用正則表達式實在難於實現,再考慮xpath,另外,在使用xpath的時候一定要選用高效的庫,比如lxml。特別是在數據量特別大的時候,效率顯得尤爲重要。
正則表達式
依賴於 re 模塊,樣板:requests和re庫
import requests
import re #導入相關的庫
url="https://www.yhjbox.com"
data = requests.get(url) #請求網頁
pattern = re.compile(r'<title>(.*?)</title>') # 查找數字
title = pattern.findall(data.text)
print(title)
bs4
全名 BeautifulSoup,是編寫 python 爬蟲常用庫之一,主要用來解析 html 標籤。官方文檔點擊
一個完整講解的案例
樣板1:
#獲取網頁文章的標題
import requests
from bs4 import BeautifulSoup as bs#導入相關的庫
url="http://www.yhjbox.com"
rec = requests.get(url=url)#請求網頁
html = rec.text #.text方法獲得字符串形式的網頁源代碼
soup = bs(html, "lxml") #對網頁進行解析
titles=soup.find_all('img',class_="thumb") #獲取文章標題 ,find是獲取第一個標題,find_all是獲取頁面所有標題
for title in titles:
print(title.get('alt'))
樣板2:
from bs4 import BeautifulSoup
import lxml
import requests
url='https://www.yhjbox.com'
data = requests.get(url)
soup = BeautifulSoup(data.content, 'lxml') #兩個參數:第一個參數是要解析的html文本,第二個參數是使用哪種解析器
#對於HTML來講就是html.parser,這是bs4自帶的解析器;也可用lxml庫來作爲解析器,效率更高,這裏正是!
title = soup.find_all('title')[0].string
print(title)
基本用法
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
soup.prettify() #格式化網頁代碼,缺少的補齊等等
soup.title #獲取<title>標籤
soup.title.string #獲取title的文本內容
soup.p #獲取p標籤
soup.p["class"] #獲取p標籤的class屬性
soup.find_all('a') #返回所有的a標籤,返回列表
xpath
是一種在 XML 文檔中查找信息的語言。使用Chrome瀏覽器來手動獲取XPath路徑,複製xpath然後粘貼到代碼裏:
test = html.xpath('//a[@href]') #匹配某種規則
樣板: requests、lxml(etree)庫
import requests
from lxml import etree
url = 'https://www.yhjbox.com'
data = requests.get(url) #請求網頁
html = etree.HTML(data.text)#解析網頁
title = html.xpath('/html/head/title/text()') #提取網頁數據
print(title)#打印title的內容
CSS
——————————————————————————————————————
通過爬取豆瓣電影top250學習requests庫的使用 - https://www.cnblogs.com/airnew/p/9981599.html
Python網絡爬蟲實戰一個完整系列(從理論到案例) https://www.jianshu.com/p/a13dc955d1f8
兩個簡短的小案例(僅僅使用幾個基本庫)
http://www.yhjbox.com/2019/08/4113/
https://mp.weixin.qq.com/s?__biz=MzIzMTU2OTkwOQ==&mid=2247485367&idx=1&sn=e1db9c77335d90dd9c92c6cf5354f53a&chksm=e8a3672ddfd4ee3b0162716751e2a2e543bfbd5df250128cc8167d134073f32a5007c59b35a3&scene=21#wechat_redirect
一個完整的案例-CSDN博客
https://blog.csdn.net/qq_36759224/article/details/101572275?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
網頁基礎手法講解+scrapy模型實例[爬蟲] 爬取豆瓣電影排行榜 - https://blog.csdn.net/makesomethings/article/details/89375462