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

Python如何爬取51cto數(shù)據(jù)并存入MySQL

 更新時(shí)間:2020年08月25日 11:18:17   作者:Keep__Studying  
這篇文章主要介紹了Python如何爬取51cto數(shù)據(jù)并存入MySQL,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

實(shí)驗(yàn)環(huán)境

1.安裝Python 3.7

2.安裝requests, bs4,pymysql 模塊

實(shí)驗(yàn)步驟1.安裝環(huán)境及模塊

可參考http://m.fzitv.net/article/194104.htm

2.編寫代碼

# 51cto 博客頁面數(shù)據(jù)插入mysql數(shù)據(jù)庫(kù)
# 導(dǎo)入模塊
import re
import bs4
import pymysql
import requests

# 連接數(shù)據(jù)庫(kù)賬號(hào)密碼
db = pymysql.connect(host='172.171.13.229',
           user='root', passwd='abc123',
           db='test', port=3306,
           charset='utf8')
# 獲取游標(biāo)
cursor = db.cursor()

def open_url(url):
  # 連接模擬網(wǎng)頁訪問
  headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
           'Chrome/57.0.2987.98 Safari/537.36'}
  res = requests.get(url, headers=headers)
  return res

# 爬取網(wǎng)頁內(nèi)容
def find_text(res):
  soup = bs4.BeautifulSoup(res.text, 'html.parser')

  # 博客名
  titles = []
  targets = soup.find_all("a", class_="tit")
  for each in targets:
    each = each.text.strip()
    if "置頂" in each:
      each = each.split(' ')[0]
    titles.append(each)

  # 閱讀量
  reads = []
  read1 = soup.find_all("p", class_="read fl on")
  read2 = soup.find_all("p", class_="read fl")
  for each in read1:
    reads.append(each.text)
  for each in read2:
    reads.append(each.text)

  # 評(píng)論數(shù)
  comment = []
  targets = soup.find_all("p", class_='comment fl')
  for each in targets:
    comment.append(each.text)

  # 收藏
  collects = []
  targets = soup.find_all("p", class_='collect fl')
  for each in targets:
    collects.append(each.text)

   # 發(fā)布時(shí)間
  dates=[]
  targets = soup.find_all("a", class_='time fl')
  for each in targets:
    each = each.text.split(':')[1]
    dates.append(each)

  # 插入sql 語句
  sql = """insert into blog (blog_title,read_number,comment_number, collect, dates)
  values( '%s', '%s', '%s', '%s', '%s');"""
  # 替換頁面 \xa0
  for titles, reads, comment, collects, dates in zip(titles, reads, comment, collects, dates):
    reads = re.sub('\s', '', reads)
    comment = re.sub('\s', '', comment)
    collects = re.sub('\s', '', collects)
    cursor.execute(sql % (titles, reads, comment, collects,dates))
    db.commit()
    pass

# 統(tǒng)計(jì)總頁數(shù)
def find_depth(res):
  soup = bs4.BeautifulSoup(res.text, 'html.parser')
  depth = soup.find('li', class_='next').previous_sibling.previous_sibling.text
  return int(depth)

# 主函數(shù)
def main():
  host = "https://blog.51cto.com/13760351"
  res = open_url(host) # 打開首頁鏈接
  depth = find_depth(res) # 獲取總頁數(shù)

  # 爬取其他頁面信息
  for i in range(1, depth + 1):
    url = host + '/p' + str(i) # 完整鏈接
    res = open_url(url) # 打開其他鏈接
    find_text(res) # 爬取數(shù)據(jù)

  # 關(guān)閉游標(biāo)
  cursor.close()
  # 關(guān)閉數(shù)據(jù)庫(kù)連接
  db.close()

if __name__ == '__main__':
  main()

3..MySQL創(chuàng)建對(duì)應(yīng)的表

CREATE TABLE `blog` (
 `row_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
 `blog_title` varchar(52) DEFAULT NULL COMMENT '博客標(biāo)題',
 `read_number` varchar(26) DEFAULT NULL COMMENT '閱讀數(shù)量',
 `comment_number` varchar(16) DEFAULT NULL COMMENT '評(píng)論數(shù)量',
 `collect` varchar(16) DEFAULT NULL COMMENT '收藏?cái)?shù)量',
 `dates` varchar(16) DEFAULT NULL COMMENT '發(fā)布日期',
 PRIMARY KEY (`row_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

4.運(yùn)行代碼,查看效果:

改進(jìn)版:

改進(jìn)內(nèi)容:

1.數(shù)據(jù)庫(kù)里面的某些字段只保留數(shù)字即可

2.默認(rèn)爬取的內(nèi)容都是字符串,存放數(shù)據(jù)庫(kù)的某些字段,最好改為整型,方便后面數(shù)據(jù)庫(kù)操作

1.代碼如下:

import re
import bs4
import pymysql
import requests

# 連接數(shù)據(jù)庫(kù)
db = pymysql.connect(host='172.171.13.229',
           user='root', passwd='abc123',
           db='test', port=3306,
           charset='utf8')
# 獲取游標(biāo)
cursor = db.cursor()

def open_url(url):
  # 連接模擬網(wǎng)頁訪問
  headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
           'Chrome/57.0.2987.98 Safari/537.36'}
  res = requests.get(url, headers=headers)
  return res

# 爬取網(wǎng)頁內(nèi)容
def find_text(res):
  soup = bs4.BeautifulSoup(res.text, 'html.parser')

  # 博客標(biāo)題
  titles = []
  targets = soup.find_all("a", class_="tit")
  for each in targets:
    each = each.text.strip()
    if "置頂" in each:
      each = each.split(' ')[0]
    titles.append(each)

  # 閱讀量
  reads = []
  read1 = soup.find_all("p", class_="read fl on")
  read2 = soup.find_all("p", class_="read fl")
  for each in read1:
    reads.append(each.text)
  for each in read2:
    reads.append(each.text)

  # 評(píng)論數(shù)
  comment = []
  targets = soup.find_all("p", class_='comment fl')
  for each in targets:
    comment.append(each.text)

  # 收藏
  collects = []
  targets = soup.find_all("p", class_='collect fl')
  for each in targets:
    collects.append(each.text)

  # 發(fā)布時(shí)間
  dates=[]
  targets = soup.find_all("a", class_='time fl')
  for each in targets:
    each = each.text.split(':')[1]
    dates.append(each)

  # 插入sql 語句
  sql = """insert into blogs (blog_title,read_number,comment_number, collect, dates)
  values( '%s', '%s', '%s', '%s', '%s');"""
  # 替換頁面 \xa0
  for titles, reads, comment, collects, dates in zip(titles, reads, comment, collects, dates):
    reads = re.sub('\s', '', reads)
    reads=int(re.sub('\D', "", reads)) #匹配數(shù)字,轉(zhuǎn)換為整型
    comment = re.sub('\s', '', comment)
    comment = int(re.sub('\D', "", comment)) #匹配數(shù)字,轉(zhuǎn)換為整型
    collects = re.sub('\s', '', collects)
    collects = int(re.sub('\D', "", collects)) #匹配數(shù)字,轉(zhuǎn)換為整型
    dates = re.sub('\s', '', dates)
    cursor.execute(sql % (titles, reads, comment, collects,dates))
    db.commit()
    pass

# 統(tǒng)計(jì)總頁數(shù)
def find_depth(res):
  soup = bs4.BeautifulSoup(res.text, 'html.parser')
  depth = soup.find('li', class_='next').previous_sibling.previous_sibling.text
  return int(depth)

# 主函數(shù)
def main():
  host = "https://blog.51cto.com/13760351"
  res = open_url(host) # 打開首頁鏈接
  depth = find_depth(res) # 獲取總頁數(shù)

  # 爬取其他頁面信息
  for i in range(1, depth + 1):
    url = host + '/p' + str(i) # 完整鏈接
    res = open_url(url) # 打開其他鏈接
    find_text(res) # 爬取數(shù)據(jù)

  # 關(guān)閉游標(biāo)
  cursor.close()
  # 關(guān)閉數(shù)據(jù)庫(kù)連接
  db.close()

#主程序入口
if __name__ == '__main__':
  main()

2.創(chuàng)建對(duì)應(yīng)表

CREATE TABLE `blogs` (
 `row_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
 `blog_title` varchar(52) DEFAULT NULL COMMENT '博客標(biāo)題',
 `read_number` int(26) DEFAULT NULL COMMENT '閱讀數(shù)量',
 `comment_number` int(16) DEFAULT NULL COMMENT '評(píng)論數(shù)量',
 `collect` int(16) DEFAULT NULL COMMENT '收藏?cái)?shù)量',
 `dates` varchar(16) DEFAULT NULL COMMENT '發(fā)布日期',
 PRIMARY KEY (`row_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

3.運(yùn)行代碼,驗(yàn)證

升級(jí)版

為了能讓小白就可以使用這個(gè)程序,可以把這個(gè)項(xiàng)目打包成exe格式的文件,讓其他人,使用電腦就可以運(yùn)行代碼,這樣非常方便!

1.改進(jìn)代碼:

#末尾修改為:
if __name__ == '__main__':
  main()
  print("\n\t\t所有數(shù)據(jù)已成功存放數(shù)據(jù)庫(kù)!!! \n")
  time.sleep(5)

2.安裝打包模塊pyinstaller(cmd安裝)

pip install pyinstaller -i https://pypi.tuna.tsinghua.edu.cn/simple/

3.Python代碼打包

1.切換到需要打包代碼的路徑下面

2.在cmd窗口運(yùn)行 pyinstaller -F test03.py (test03為項(xiàng)目名稱)

4.查看exe包

在打包后會(huì)出現(xiàn)dist目錄,打好包就在這個(gè)目錄里面

5.運(yùn)行exe包,查看效果

檢查數(shù)據(jù)庫(kù)

總結(jié):

1.這一篇博客,是在上一篇的基礎(chǔ)上改進(jìn)的,步驟是先爬取首頁的信息,再爬取其他頁面信息,最后在改進(jìn)細(xì)節(jié),打包exe文件

2.我們爬取網(wǎng)頁數(shù)據(jù)大多數(shù)還是存放到數(shù)據(jù)庫(kù)的,所以這種方法很實(shí)用。

3.其實(shí)在此博客的基礎(chǔ)上還是可以改進(jìn)的,重要的是掌握方法即可。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • pytorch交叉熵?fù)p失函數(shù)的weight參數(shù)的使用

    pytorch交叉熵?fù)p失函數(shù)的weight參數(shù)的使用

    這篇文章主要介紹了pytorch交叉熵?fù)p失函數(shù)的weight參數(shù)的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • python+opencv 讀取文件夾下的所有圖像并批量保存ROI的方法

    python+opencv 讀取文件夾下的所有圖像并批量保存ROI的方法

    今天小編就為大家分享一篇python+opencv 讀取文件夾下的所有圖像并批量保存ROI的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • python調(diào)用fortran模塊

    python調(diào)用fortran模塊

    本文給大家介紹的是在Python中調(diào)用fortran代碼,主要是用到了f2py這個(gè)程序,十分的實(shí)用,有需要的小伙伴可以參考下
    2016-04-04
  • 一文詳解Python中的Map,Filter和Reduce函數(shù)

    一文詳解Python中的Map,Filter和Reduce函數(shù)

    這篇文章主要介紹了一文詳解Python中的Map,Filter和Reduce函數(shù),本文重點(diǎn)介紹Python中的三個(gè)特殊函數(shù)Map,Filter和Reduce,以及如何使用它們進(jìn)行代碼編程
    2022-08-08
  • 深入了解Python的類與模塊化

    深入了解Python的類與模塊化

    這篇文章主要介紹了Python中的面向?qū)ο缶幊谭妒揭约澳K化思想,并給出相應(yīng)的實(shí)戰(zhàn)示例及解釋,對(duì)我們的學(xué)習(xí)和工作都有一定的價(jià)值,感興趣的小伙伴可以了解一下
    2021-12-12
  • 基于python實(shí)現(xiàn)聊天室程序

    基于python實(shí)現(xiàn)聊天室程序

    這篇文章主要為大家詳細(xì)介紹了基于python實(shí)現(xiàn)聊天室程序,該程序由客戶端與服務(wù)器構(gòu)成,使用UDP服務(wù),實(shí)現(xiàn)了群發(fā)、私發(fā)、點(diǎn)對(duì)點(diǎn)文件互傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • 使用Python IDLE進(jìn)行Debug調(diào)試的圖文步驟

    使用Python IDLE進(jìn)行Debug調(diào)試的圖文步驟

    本文主要介紹了使用Python IDLE進(jìn)行Debug調(diào)試的圖文步驟,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-02-02
  • Python圖像銳化與邊緣檢測(cè)之Sobel與Laplacian算子詳解

    Python圖像銳化與邊緣檢測(cè)之Sobel與Laplacian算子詳解

    圖像銳化和邊緣檢測(cè)主要包括一階微分銳化和二階微分銳化,本文主要講解常見的圖像銳化和邊緣檢測(cè)方法,即Sobel算子和Laplacian算子,感興趣的可以了解一下
    2022-12-12
  • Python中pip安裝非PyPI官網(wǎng)第三方庫(kù)的方法

    Python中pip安裝非PyPI官網(wǎng)第三方庫(kù)的方法

    這篇文章主要介紹了Python中pip安裝非PyPI官網(wǎng)第三方庫(kù)的方法,pip最新的版本(1.5以上的版本), 出于安全的考 慮,pip不允許安裝非PyPI的URL,本文就給出兩種解決方法,需要的朋友可以參考下
    2015-06-06
  • Python面向?qū)ο蟪绦蛟O(shè)計(jì)之私有屬性及私有方法示例

    Python面向?qū)ο蟪绦蛟O(shè)計(jì)之私有屬性及私有方法示例

    這篇文章主要介紹了Python面向?qū)ο蟪绦蛟O(shè)計(jì)之私有屬性及私有方法,結(jié)合實(shí)例形式分析了Python私有屬性及私有方法的相關(guān)使用方法及操作注意事項(xiàng),需要的朋友可以參考下
    2019-04-04

最新評(píng)論

嘉鱼县| 兴宁市| 银川市| 隆德县| 辽中县| 依兰县| 乡城县| 宁强县| 永德县| 开远市| 宜宾市| 绥江县| 丹巴县| 巫山县| 湖南省| 德钦县| 高台县| 武胜县| 大田县| 临漳县| 富蕴县| 威信县| 南漳县| 英德市| 叙永县| 华容县| 本溪市| 建水县| 遂平县| 江陵县| 出国| 类乌齐县| 梁平县| 正镶白旗| 吉木萨尔县| 荔波县| 建阳市| 临猗县| 平乐县| 屏南县| 盈江县|