最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)上篇

 更新時(shí)間:2023年01月11日 17:05:27   作者:艾派森  
這篇文章主要介紹了Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)上篇,本文章內(nèi)容詳細(xì),通過(guò)案例可以更好的理解爬蟲(chóng)的相關(guān)知識(shí),七個(gè)例子分為了三部分,本次為上篇,共有二道題,需要的朋友可以參考下

本次的7個(gè)python爬蟲(chóng)小案例涉及到了re正則、xpath、beautiful soup、selenium等知識(shí)點(diǎn),非常適合剛?cè)腴T(mén)python爬蟲(chóng)的小伙伴參考學(xué)習(xí)。

前言

關(guān)于Python7個(gè)爬蟲(chóng)小案例的文章分為三篇,本篇為上篇,共兩題,其余兩篇內(nèi)容請(qǐng)關(guān)注!

題目一:

使用正則表達(dá)式和文件操作爬取并保存“百度貼吧”某帖子全部?jī)?nèi)容(該帖不少于5頁(yè))

 本次選取的是百度貼吧中的NBA吧中的一篇帖子,帖子標(biāo)題是“克萊和哈登,誰(shuí)歷史地位更高”。爬取的目標(biāo)是帖子里面的回復(fù)內(nèi)容。

源程序和關(guān)鍵結(jié)果截圖:

import csv
import requests
import re
import time
 
def main(page):
    url = f'https://tieba.baidu.com/p/7882177660?pn={page}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
    }
    resp = requests.get(url,headers=headers)
    html = resp.text
    # 評(píng)論內(nèi)容
    comments = re.findall('style="display:;">                    (.*?)</div>',html)
    # 評(píng)論用戶
    users = re.findall('class="p_author_name j_user_card" href=".*?" rel="external nofollow"  target="_blank">(.*?)</a>',html)
    # 評(píng)論時(shí)間
    comment_times = re.findall('樓</span><span class="tail-info">(.*?)</span><div',html)
    for u,c,t in zip(users,comments,comment_times):
        # 篩選數(shù)據(jù),過(guò)濾掉異常數(shù)據(jù)
        if 'img' in c or 'div' in c or len(u)>50:
            continue
        csvwriter.writerow((u,t,c))
        print(u,t,c)
    print(f'第{page}頁(yè)爬取完畢')
 
if __name__ == '__main__':
    with open('01.csv','a',encoding='utf-8')as f:
        csvwriter = csv.writer(f)
        csvwriter.writerow(('評(píng)論用戶','評(píng)論時(shí)間','評(píng)論內(nèi)容'))
        for page in range(1,8):  # 爬取前7頁(yè)的內(nèi)容
            main(page)
            time.sleep(2)

題目二:

實(shí)現(xiàn)多線程爬蟲(chóng)爬取某小說(shuō)部分章節(jié)內(nèi)容并以數(shù)據(jù)庫(kù)存儲(chǔ)(不少于10個(gè)章節(jié)) 

 本次選取的小說(shuō)網(wǎng)址是全本小說(shuō)網(wǎng)https://www.qb5.tw/,這里我們選取第一篇小說(shuō)進(jìn)行爬取

然后通過(guò)分析網(wǎng)頁(yè)源代碼分析每章小說(shuō)的鏈接

找到鏈接的位置后,我們使用Xpath來(lái)進(jìn)行鏈接和每一章標(biāo)題的提取

在這里,因?yàn)樯婕暗蕉啻问褂胷equests發(fā)送請(qǐng)求,所以這里我們把它封裝成一個(gè)函數(shù),便于后面的使用

每一章的鏈接獲取后,我們開(kāi)始進(jìn)入小說(shuō)章節(jié)內(nèi)容頁(yè)面進(jìn)行分析

通過(guò)網(wǎng)頁(yè)分析,小說(shuō)內(nèi)容都在網(wǎng)頁(yè)源代碼中,屬于靜態(tài)數(shù)據(jù)

這里我們選用re正則表達(dá)式進(jìn)行數(shù)據(jù)提取,并對(duì)最后的結(jié)果進(jìn)行清洗

然后我們需要將數(shù)據(jù)保存到數(shù)據(jù)庫(kù)中,這里我將爬取的數(shù)據(jù)存儲(chǔ)到mysql數(shù)據(jù)庫(kù)中,先封住一下數(shù)據(jù)庫(kù)的操作

接著將爬取到是數(shù)據(jù)進(jìn)行保存

最后一步就是使用多線程來(lái)提高爬蟲(chóng)效率,這里我們創(chuàng)建了5個(gè)線程的線程池

 源代碼及結(jié)果截圖:

import requests
from lxml import etree
import re
import pymysql
from time import sleep
from concurrent.futures import ThreadPoolExecutor
 
def get_conn():
    # 創(chuàng)建連接
    conn = pymysql.connect(host="127.0.0.1",
                           user="root",
                           password="root",
                           db="novels",
                           charset="utf8")
    # 創(chuàng)建游標(biāo)
    cursor = conn.cursor()
    return conn, cursor
 
def close_conn(conn, cursor):
    cursor.close()
    conn.close()
 
def get_xpath_resp(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}
    resp = requests.get(url, headers=headers)
    tree = etree.HTML(resp.text)  # 用etree解析html
    return tree,resp
 
def get_chapters(url):
    tree,_ = get_xpath_resp(url)
    # 獲取小說(shuō)名字
    novel_name = tree.xpath('//*[@id="info"]/h1/text()')[0]
    # 獲取小說(shuō)數(shù)據(jù)節(jié)點(diǎn)
    dds = tree.xpath('/html/body/div[4]/dl/dd')
    title_list = []
    link_list = []
    for d in dds[:15]:
        title = d.xpath('./a/text()')[0]  # 章節(jié)標(biāo)題
        title_list.append(title)
        link = d.xpath('./a/@href')[0]   # 章節(jié)鏈接
        chapter_url = url +link  # 構(gòu)造完整鏈接
        link_list.append(chapter_url)
    return title_list,link_list,novel_name
 
def get_content(novel_name,title,url):
    try:
        cursor = None
        conn = None
        conn, cursor = get_conn()
        # 插入數(shù)據(jù)的sql
        sql = 'INSERT INTO novel(novel_name,chapter_name,content) VALUES(%s,%s,%s)'
        tree,resp = get_xpath_resp(url)
        # 獲取內(nèi)容
        content = re.findall('<div id="content">(.*?)</div>',resp.text)[0]
        # 對(duì)內(nèi)容進(jìn)行清洗
        content = content.replace('<br />','\n').replace('&nbsp;',' ').replace('全本小說(shuō)網(wǎng) www.qb5.tw,最快更新<a  rel="external nofollow" >宇宙職業(yè)選手</a>最新章節(jié)!<br><br>','')
        print(title,content)
        cursor.execute(sql,[novel_name,title,content])  # 插入數(shù)據(jù)
        conn.commit()  # 提交事務(wù)保存數(shù)據(jù)
    except:
        pass
    finally:
        sleep(2)
        close_conn(conn, cursor)  # 關(guān)閉數(shù)據(jù)庫(kù)
 
 
if __name__ == '__main__':
    # 獲取小說(shuō)名字,標(biāo)題鏈接,章節(jié)名稱
    title_list, link_list, novel_name = get_chapters('https://www.qb5.tw/book_116659/')
    with ThreadPoolExecutor(5) as t:  # 創(chuàng)建5個(gè)線程
        for title,link in zip(title_list,link_list):
            t.submit(get_content, novel_name,title,link)  # 啟動(dòng)線程

到此這篇關(guān)于Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)上篇的文章就介紹到這了,其他兩個(gè)部分的內(nèi)容(中、下篇)請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

阳城县| 昭苏县| 苏尼特左旗| 台前县| 扎囊县| 平凉市| 江山市| 永修县| 三台县| 龙山县| 五大连池市| 德安县| 宜丰县| 仙居县| 长丰县| 林州市| 昌乐县| 调兵山市| 闻喜县| 丹巴县| 稻城县| 应城市| 绍兴县| 汽车| 姚安县| 桐柏县| 太仓市| 六枝特区| 长武县| 淮南市| 邹城市| 阿克陶县| 衡南县| 林周县| 二连浩特市| 凌云县| 瓮安县| 临猗县| 榆树市| 晋城| 开化县|