前言:
Python的爬蟲相當方便,關於快速上手,建議這部分需要反覆的練習,這部分也是自己學習Python這門語言的目的。
常用的模塊下載:
- pip install send2trash
- pip install requests
- pip install beautifulsoup4
- pip install selenium
- pip install openpyxl
- pip install PyPDF2
- pip install python-docx
- pip installI imapclient
- pip install twilio
- pip install pillow
- pip install pyobjc-core(僅在OSX上)
- pip install pyobjc(僅在OSX上)
- pip install python3-xlib(僅在Linux)
- pip install pyautogui
爬蟲代碼:
練習一
#! python3
# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
url = 'https://xkcd.com' # starting url
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
while not url.endswith('#'):
# Download the page.
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = 'https:' + comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
# Save the image to ./xkcd.
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
# Get the Prev button's url.
prevLink = soup.select('a[rel="prev"]')[0]
url = 'https://xkcd.com' + prevLink.get('href')
print('Done.')
結果:
遇到的問題:
由於連接方在一段時間後沒有正確答覆或連接的主機沒有反應,連接嘗試失敗問題
解決辦法:
1、以管理員身份打開命令提示符
netsh winsock reset
之後重啓。
2、爬取的網址是否爲國外網址,比如本例子,由於是國外的網址,同時手機流量不穩定也有可能出現超時
二、練習二:爬蟲,爬小說:
前期準備工作:
pip install tqdm
pip install tqdm
pip install lxml
pip install beautifulsoup4
實現代碼:
import requests
import time
from tqdm import tqdm
from bs4 import BeautifulSoup
#根據目錄查找出具體章節內容
def get_content(target):
req = requests.get(url = target)
req.encoding = 'utf-8'
html = req.text
bf = BeautifulSoup(html, 'lxml')
texts = bf.find('div', id='content')
content = texts.text.strip().split('\xa0'*4)
return content
#查看爬取的章節找到章節獲取章節名稱、鏈接,調用鏈接內容
if __name__ == '__main__':
server = 'https://www.xsbiquge.com'
book_name = '詭祕之主.txt'
target = 'https://www.xsbiquge.com/15_15338/'
req = requests.get(url = target)
req.encoding = 'utf-8'
html = req.text
chapter_bs = BeautifulSoup(html, 'lxml')
chapters = chapter_bs.find('div', id='list')#查找id爲list 方便後面查a 定位
chapters = chapters.find_all('a')
for chapter in tqdm(chapters):
chapter_name = chapter.string
url = server + chapter.get('href')
content = get_content(url) #獲取章節內容詳情
with open(book_name, 'a', encoding='utf-8') as f:
f.write(chapter_name)
f.write('\n')
f.write('\n'.join(content))
f.write('\n')
結果演示
小結:
文件讀寫,靜態頁面,入門練手
三、爬取漫畫練習
最最最低級的反爬蟲:不能直接按F12:
網址前綴+view-source:
分析代碼:
難點:
- js動態解析:就是沒給出具體的圖片信息,往往需要正則化解析地址。
- 下載圖片遇到站內訪問的情況。
其中:一種典型的通過Referer的反扒爬蟲手段
Referer可以理解爲來路,先打開章節URL鏈接,再打開圖片鏈接。打開圖片的時候,Referer的信息裏保存的是章節URL。
比如:動漫之家網站的做法就是,站內的用戶訪問這個圖片,我就給他看,從其它地方過來的用戶,我就不給他看。
是不是站內用戶,就是根據Referer進行簡單的判斷。
這就是很典型的,反爬蟲手段!
解決辦法:
也簡單,它需要啥,咱給它就完了。