這幾天工作不忙,寫一個(gè)爬蟲程序試試介却。起初想爬美團(tuán)的外賣商家數(shù)據(jù)砰识,但是ajax那的_token參數(shù)一時(shí)半會(huì)搞不定能扒,先寫個(gè)簡(jiǎn)單的。對(duì)于我這python新手也是收獲不小辫狼。
先放代碼初斑,是從一個(gè)網(wǎng)站下載小說的程序。
# -*- coding:utf-8 -*-
from urllib import request
from bs4 import BeautifulSoup
def getResponse(url):
head = {}
# 寫入U(xiǎn)ser Agent信息
head[
'User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'
url_request = request.Request(url, headers=head)
url_response = request.urlopen(url_request)
//response的header表明內(nèi)容'utf-8'的膨处,header信息在后面
return url_response.read().decode('utf-8')
# 筆趣閣??貌似也是冒牌的~
url = 'https://www.qu.la/book/61600/'
response = getResponse(url)
# print(response)
soup = BeautifulSoup(response, 'lxml')
p = soup.find('dt', text='《太初》正文卷')
print(p)
chapter = p.find_next('dd')
# for chapter in chapters:
print(chapter.a['href'])
print(chapter.a.text)
url = "https://www.qu.la" + chapter.a['href']
print('url is ' + url)
response = getResponse(url)
soup = BeautifulSoup(response, 'lxml')
content = soup.find('div', id="content")
strs = content.text.split("\n")
print('!' * 50)
with open('test.txt', 'w', encoding='gbk', errors='ignore') as f:
for str_ in strs:
str_ = str_.strip()
if (str_ == '' or str_ == '\n'):
continue
print(type(str_))
f.write(str_)
print('*' * 50)
其中的知識(shí)點(diǎn)主要是BeautifulSoup的使用见秤,以及編碼格式的問題。BeautifulSoup的使用網(wǎng)上的例子很多真椿,不再贅述鹃答,主要談一下編碼格式
的問題吧。
看了很多python編碼格式的文章突硝,但是和自己以前的理解有些不同测摔,這里談一下自己的理解。
我認(rèn)為編碼格式是針對(duì)二進(jìn)制的bytes數(shù)組的解恰,而不是針對(duì)str的锋八。在系統(tǒng)內(nèi)部,數(shù)據(jù)是以Unicode格式的二進(jìn)制存在的护盈,我們看到的str是這些二進(jìn)制表達(dá)的意思挟纱。這些str要落地(如存磁盤,網(wǎng)絡(luò)傳輸腐宋,控制臺(tái)打印等)時(shí)紊服,這是輸出,需要轉(zhuǎn)換為二進(jìn)制然后存儲(chǔ)/傳輸胸竞,這里需要做的是encode欺嗤。而作輸入時(shí),是二進(jìn)制轉(zhuǎn)化為為str撤师,這里做的是decode剂府。因此可以說二進(jìn)制流是哪種編碼方式的,而不是str剃盾。而且一種編碼方式二進(jìn)制流不能直接變?yōu)榱硪环N編碼方式的二進(jìn)制流腺占,需要先變?yōu)閟tr
在本段代碼中,爬到的內(nèi)容是UTF-8格式的痒谴,因此作了一次decode衰伯,存儲(chǔ)時(shí)放到了gbk的文件,作了一次encode积蔚。
Date: Fri, 03 Aug 2018 02:04:49 GMT
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Content-Length: 145886
Age: 149
X-Via: 1.1 zhjhzhdx19:1 (Cdn Cache Server V2.0), 1.1 PSmgnyNY2li89:0 (Cdn Cache Server V2.0)
Connection: close
X-Dscp-Value: 0