現(xiàn)在Python語言大火嗓违,在網(wǎng)絡爬蟲、人工智能图贸、大數(shù)據(jù)等領域都有很好的應用蹂季。今天我向大家介紹一下Python爬蟲的一些知識和常用類庫的用法冕广,希望能對大家有所幫助。
其實爬蟲這個概念很簡單偿洁,基本可以分成以下幾個步驟:
- 發(fā)起網(wǎng)絡請求
- 獲取網(wǎng)頁
- 解析網(wǎng)頁獲取數(shù)據(jù)
發(fā)起網(wǎng)絡請求這個步驟常用的類庫有標準庫urllib以及Python上常用的requests庫撒汉。解析網(wǎng)頁常用的類庫有的BeautifulSoup。另外requests的作者還開發(fā)了另一個很好用的庫requests-html涕滋,提供了發(fā)起請求和解析網(wǎng)頁的二合一功能睬辐,開發(fā)小型爬蟲非常方便。另外還有一些專業(yè)的爬蟲類庫宾肺,其中比較出名的就是scrapy溯饵。本文將會簡單介紹一下這些類庫,之后還會專門寫一篇文章介紹scrapy的用法锨用。
標準庫urllib
首先先來看標準庫urllib丰刊。標準庫的優(yōu)點是Python自帶的,不需要安裝任何第三方庫黔酥,缺點就是urllib屬于偏底層的庫藻三,使用起來比較麻煩。下面是urllib發(fā)起請求的一個簡單例子跪者,大家看看就好棵帽。可以看到為了發(fā)起一個簡單的請求渣玲,我們需要創(chuàng)建opener逗概、request、ProxyHandler等好幾個對象忘衍,比較麻煩逾苫。
import urllib.request as request
import requests
proxies = {
'https': 'https://127.0.0.1:1080',
'http': 'http://127.0.0.1:1080'
}
headers = {
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'
}
print('--------------使用urllib--------------')
url = 'http://www.google.com'
opener = request.build_opener(request.ProxyHandler(proxies))
request.install_opener(opener)
req = request.Request(url, headers=headers)
response = request.urlopen(req)
print(response.read().decode())
requests
requests是Kenneth Reitz大神的著名作品之一,優(yōu)點就是極度簡單和好用枚钓。首先來安裝requests铅搓。
pip install requests
下面是一個簡單的例子,和上面urllib示例代碼實現(xiàn)的功能相同搀捷,但是代碼量少多了星掰,也更易讀。
print('--------------使用requests--------------')
response = requests.get('https://www.google.com', headers=headers, proxies=proxies)
response.encoding = 'utf8'
print(response.text)
requests還可以方便的發(fā)送表單數(shù)據(jù)嫩舟,模擬用戶登錄氢烘。返回的Response對象還包含了狀態(tài)碼、header家厌、raw播玖、cookies等很多有用的信息。
data = {
'name': 'yitian',
'age': 22,
'friends': ['zhang3', 'li4']
}
response = requests.post('http://httpbin.org/post', data=data)
pprint(response.__dict__)
print(response.text)
關于requests我就不多做介紹了饭于,因為它有中文文檔蜀踏,雖然比官方落后幾個小版本號维蒙,不過無傷大雅,大家可以放心參閱脓斩。
http://cn.python-requests.org/zh_CN/latest/
beautifulsoup
利用前面介紹的requests類庫木西,我們可以輕易地獲取HTML代碼,但是為了從HTML中找到所需的數(shù)據(jù)随静,我們還需要HTML/XML解析庫八千,BeautifulSoup就是這么一個常用的庫。首先先來安裝它:
pip install beautifulsoup4
這次就用我簡書主頁作為例子燎猛,爬取一下我簡書的文章列表恋捆。首先先用requests獲取到網(wǎng)頁內(nèi)容。
from pprint import pprint
import bs4
import requests
headers = {
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'
}
url = 'http://www.reibang.com/u/7753478e1554'
response = requests.get(url, headers=headers)
然后就是BeautifulSoup的代碼了重绷。在使用BeautifulSoup的時候首先需要創(chuàng)建一個HTML樹沸停,然后從樹中查找節(jié)點。BeautifulSoup主要有兩種查找節(jié)點的辦法昭卓,第一種是使用find和find_all方法愤钾,第二種方法是使用select方法用css選擇器。拿到節(jié)點之后候醒,用contents去獲取它的子節(jié)點能颁,如果子節(jié)點是文本,就會拿到文本值倒淫,注意這個屬性返回的是列表伙菊,所以要加[0]。
html = bs4.BeautifulSoup(response.text, features='lxml')
note_list = html.find_all('ul', class_='note-list', limit=1)[0]
for a in note_list.select('li>div.content>a.title'):
title = a.contents[0]
link = f'http://www.reibang.com{a["href"]}'
print(f'《{title}》,{link}')
BeautifulSoup也有中文文檔敌土,同樣也是稍微落后兩個小版本镜硕,影響不大。
https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/
requests-html
這個類庫是requests的兄弟返干,同樣也是Kenneth Reitz大神的作品兴枯。它將請求網(wǎng)頁和解析網(wǎng)頁結(jié)合到了一起。本來如果你用requests的話只能請求網(wǎng)頁矩欠,為了解析網(wǎng)頁還得使用BeautifulSoup這樣的解析庫∧罨校現(xiàn)在只需要requests-html一個庫就可以辦到。
首先先來安裝晚顷。
pip install requests-html
然后我們來看看用requests-html如何重寫上面這個例子。
from requests_html import HTMLSession
from pprint import pprint
url = 'http://www.reibang.com/u/7753478e1554'
headers = {
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'
}
session = HTMLSession()
r = session.get(url, headers=headers)
note_list = r.html.find('ul.note-list', first=True)
for a in note_list.find('li>div.content>a.title'):
title = a.text
link = f'http://www.reibang.com{a.attrs["href"]}'
print(f'《{title}》,{link}')
requests-html除了可以使用css選擇器來搜索以外疗疟,還可以使用xpath來查找该默。
for a in r.html.xpath('//ul[@class="note-list"]/li/div[@class="content"]/a[@class="title"]'):
title = a.text
link = f'http://www.reibang.com{a.attrs["href"]}'
print(f'《{title}》,{link}')
requests-html還有一個很有用的特性就是瀏覽器渲染。有些網(wǎng)頁是異步加載的策彤,直接用爬蟲去爬只能得到一個空頁面栓袖,因為數(shù)據(jù)是靠瀏覽器運行JS腳本異步加載的匣摘,這時候就需要瀏覽器渲染了。而瀏覽器渲染用requests-html做非常簡單裹刮,只要多調(diào)用一個render函數(shù)即可音榜。render函數(shù)有兩個參數(shù),分別指定頁面下滑次數(shù)和暫停時間捧弃。render函數(shù)第一次運行的時候赠叼,requests-html會下載一個chromium瀏覽器,然后用它渲染頁面违霞。
簡書的個人文章頁面也是一個異步加載的例子嘴办,默認只會顯示最近幾篇文章,通過瀏覽器渲染模擬頁面下滑买鸽,我們可以得到所有文章列表涧郊。
session = HTMLSession()
r = session.get(url, headers=headers)
# render函數(shù)指示requests-html用chromium瀏覽器渲染頁面
r.html.render(scrolldown=50, sleep=0.2)
for a in r.html.xpath('//ul[@class="note-list"]/li/div[@class="content"]/a[@class="title"]'):
title = a.text
link = f'http://www.reibang.com{a.attrs["href"]}'
print(f'《{title}》,{link}')
類似的,今日頭條的個人頁面也是異步加載的眼五,所以也得調(diào)用render函數(shù)妆艘。
from requests_html import HTMLSession
headers = {
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'
}
session = HTMLSession()
r = session.get('https://www.toutiao.com/c/user/6662330738/#mid=1620400303194116', headers=headers)
r.html.render()
for i in r.html.find('div.rbox-inner a'):
title = i.text
link = f'https://www.toutiao.com{i.attrs["href"]}'
print(f'《{title}》 {link}')
最后是requests-html的官網(wǎng)地址以及中文文檔。
https://html.python-requests.org/
https://cncert.github.io/requests-html-doc-cn/#/?id=requests-html
scrapy
以上介紹的幾個框架都是各自有各自的作用看幼,把它們結(jié)合起來可以達到編寫爬蟲的目的批旺,但是要說專業(yè)的爬蟲框架,還是得談談scrapy桌吃。作為一個著名的爬蟲框架朱沃,scrapy將爬蟲模型框架化和模塊化,利用scrapy茅诱,我們可以迅速生成功能強大的爬蟲逗物。
不過scrapy概念眾多,要仔細說還得專門開篇文章瑟俭,這里就只簡單演示一下翎卓。首先安裝scrapy,如果是Windows系統(tǒng)摆寄,還需要安裝pypiwin32失暴。
pip install scrapy
pip install pypiwin32
然后創(chuàng)建scrapy項目并添加一個新爬蟲。
scrapy startproject myproject
cd myproject
scrapy genspider my jianshu.com
打開配置文件settings.py
,設置用戶代理,否則會遇到403錯誤帅韧。
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'
然后修改一下爬蟲押袍。
# -*- coding: utf-8 -*-
import scrapy
class JianshuSpider(scrapy.Spider):
name = 'jianshu'
allowed_domains = ['jianshu.com']
start_urls = ['http://www.reibang.com/u/7753478e1554']
def parse(self, response):
for article in response.css('div.content'):
yield {
'title': article.css('a.title::text').get(),
'link': 'http://www.reibang.com' + article.xpath('a[@class="title"]/@href').get()
}
最后運行一下爬蟲。
scrapy crawl my
以上就是這篇文章的內(nèi)容了,希望對大家有所幫助。