溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

小白的python爬蟲(chóng),40代碼教你爬取豆瓣小說(shuō)

發(fā)布時(shí)間:2020-06-26 22:46:36 來(lái)源:網(wǎng)絡(luò) 閱讀:1290 作者:星火燎愿 欄目:編程語(yǔ)言

這篇文章寫(xiě)了很久了,一直沒(méi)有發(fā)布;
爬蟲(chóng)學(xué)的差不多了,覺(jué)得這篇文章對(duì)新手實(shí)踐還是有些作用的。畢竟這也是我剛學(xué)爬蟲(chóng)的時(shí)候練習(xí)的,爬取了比較好爬的網(wǎng)站,也比較經(jīng)典;多余的解釋不說(shuō)了,代碼里每一行都有注釋?zhuān)忉尩暮芮宄?br/>后續(xù)有時(shí)間的話還會(huì)發(fā)布一些爬蟲(chóng)文章的;

=============================================

直接上代碼:

import requests
from bs4 import BeautifulSoup
from lxml import etree
#抓取豆瓣小說(shuō)的 書(shū)名、評(píng)分;

page = 0            #定義頁(yè)數(shù)初始值;
lists_book = []     #定義書(shū)名列表;
lists_grade = []    #定義評(píng)分的列表;
for u in range(0,20):   #循環(huán)20次,每一次循環(huán)爬取一頁(yè),即:抓取20頁(yè);
    basic_url = 'https://book.douban.com/tag/%E5%B0%8F%E8%AF%B4?start=' + str(page) + '&type=T'
    page += 20      #每循環(huán)一次 +20,適應(yīng)鏈接變化;

    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
    }
    #發(fā)送請(qǐng)求
    response = requests.get(basic_url, headers=headers, timeout=10)     #requests請(qǐng)求;
    response.encoding = 'utf-8'     #設(shè)置編碼
    htm = response.text     #返回text文本;

    #解析請(qǐng)求
    selector = etree.HTML(htm)      #利用 etree.HTML 初始化
    book_name = selector.xpath('//*[@id="subject_list"]/ul/li/div[2]/h3/a/text()')  #獲取書(shū)名
    grade = selector.xpath('//*[@id="subject_list"]/ul/li/div[2]/div[2]/span[2]/text()')    #獲取評(píng)分;

    #將書(shū)名存入到lists_book列表;
    for i in book_name:
        lists_book.append(i.strip())     #去除字符串空格,存入列表;
        while '' in lists_book:      #如果列表中有空元素,則刪除空元素;
            lists_book.remove('')
    #將評(píng)分存入到lists_grade列表;
    for i in grade:
        lists_grade.append(i.strip())     #去除字符串空格,存入列表;
        while '' in lists_grade:      #如果列表中有空元素,則刪除空元素;
            lists_grade.remove('')

print(lists_book)           #輸出爬取的書(shū)名列表;
print(len(lists_book))      #輸出列表的長(zhǎng)度,即:爬取了多少本書(shū)
print(lists_grade)          #輸出評(píng)分的列表;
print(len(lists_grade))     #輸出評(píng)分列表的長(zhǎng)度;為了和書(shū)的數(shù)目核對(duì),防止偏差;
print("評(píng)分最高: "+ str(max(lists_grade)) + "\n" + "書(shū)名: " + lists_book[lists_grade.index(max(lists_grade))])

運(yùn)行后結(jié)果輸出到了屏幕上,并沒(méi)有存入數(shù)據(jù)庫(kù),后續(xù)需要也可以繼續(xù)添加代碼將爬取結(jié)果存入數(shù)據(jù)庫(kù);

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI