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

Python爬蟲爬取、解析數(shù)據(jù)操作示例

 更新時間:2020年03月27日 11:39:07   作者:OldKind超  
這篇文章主要介紹了Python爬蟲爬取、解析數(shù)據(jù)操作,結(jié)合實例形式分析了Python爬蟲爬取、解析、存儲數(shù)據(jù)相關(guān)操作技巧與注意事項,需要的朋友可以參考下

本文實例講述了Python爬蟲爬取、解析數(shù)據(jù)操作。分享給大家供大家參考,具體如下:

爬蟲 當(dāng)當(dāng)網(wǎng) http://search.dangdang.com/?key=python&act=input&page_index=1

  1. 獲取書籍相關(guān)信息
  2. 面向?qū)ο笏枷?/li>
  3. 利用不同解析方式和存儲方式

引用相關(guān)庫

import requests
import re
import csv
import pymysql
from bs4 import BeautifulSoup
from lxml import etree
import lxml
from lxml import html

類代碼實現(xiàn)部分

class DDSpider(object):
  #對象屬性 參數(shù) 關(guān)鍵字 頁數(shù)
  def __init__(self,key='python',page=1):
    self.url = 'http://search.dangdang.com/?key='+key+'&act=input&page_index={}'
    self.page = page
    self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'}

    
  #私有對象方法
  def __my_url(self):
    my_url = []
    if self.page < 1:
      my_page = 2
    else:
      my_page = self.page+1
    #循環(huán)遍歷每一頁
    for i in range(1,my_page):
      my_url.append(self.url.format(i))
    return my_url
  
  #私有對象方法 請求數(shù)據(jù)
  def __my_request(self,url,parser_type):
    #循環(huán)遍歷每一頁
    response = requests.get(url=url,headers=self.headers)
    if response.status_code == 200:
      return self.__my_parser(response.text,parser_type)
    else:
      return None
    
  #私有對象方法 解析數(shù)據(jù) 1 利用正則 2 bs4 3 xpath
  def __my_parser(self,html,my_type=1):
    if my_type == 1:
      pattern = re.compile('<p.*?class=[\'\"]name[\'\"].*?name=[\'\"]title[\'\"].*?<a.*?title=[\'\"](.*?)[\'\"].*?href=[\'\"](.*?)[\'\"].*?name=[\'\"]itemlist-title[\'\"].*?<p class=[\'\"]detail[\'\"].*?>(.*?)</p>.*?<span.*?class=[\'\"]search_now_price[\'\"].*?>(.*?)</span>.*?<p.*?class=[\'\"]search_book_author[\'\"].*?><span>.*?<a.*?name=[\'\"]itemlist-author[\'\"].*?title=[\'\"](.*?)[\'\"].*?</span>',re.S)
      result = re.findall(pattern,html)
    elif my_type == 2:
      soup = BeautifulSoup(html,'lxml')
      result = []
      title_url = soup.find_all('a',attrs={'name':'itemlist-title'})
      for i in range(0,len(title_url)):
        title = soup.find_all('a',attrs={'name':'itemlist-title'})[i].attrs['title']
        url = soup.find_all('a',attrs={'name':'itemlist-title'})[i].attrs['href']
        price = soup.find_all('span',attrs={'class':'search_now_price'})[i].get_text()
        author = soup.find_all('a',attrs={'name':'itemlist-author'})[i].attrs['title']
        desc = soup.find_all('p',attrs={'class':'detail'})[i].get_text()
        my_tuple = (title,url,desc,price,author)
        result.append(my_tuple)
    else:
      html = etree.HTML(html)
      li_all = html.xpath('//div[@id="search_nature_rg"]/ul/li')
      result = []
      for i in range(len(li_all)):
        title = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="name"]/a/@title'.format(i+1))
        url = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="name"]/a/@href'.format(i+1))
        price = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]//span[@class="search_now_price"]/text()'.format(i+1))
        author_num = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="search_book_author"]/span[1]/a'.format(i+1))
        if len(author_num) != 0:
          #有作者 a標(biāo)簽
          author = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="search_book_author"]/span[1]/a[1]/@title'.format(i+1))
        else:
          #沒有作者 a標(biāo)簽
          author = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="search_book_author"]/span[1]/text()'.format(i+1))
        desc = html.xpath('//div[@id="search_nature_rg"]/ul/li[{}]/p[@class="detail"]/text()'.format(i+1))
        my_tuple = (" ".join(title)," ".join(url)," ".join(desc)," ".join(price)," ".join(author))
        result.append(my_tuple)
        
    return result
  
  #私有對象方法 存儲數(shù)據(jù) 1 txt 2 csv 3 mysql
  def __my_save(self,data,save_type=1):
    #循環(huán)遍歷
    for value in data:
      if save_type == 1:
        with open('ddw.txt','a+',encoding="utf-8") as f:
          f.write('【名稱】:{}【作者】:{}【價格】:{}【簡介】:{}【鏈接】:{}'.format(value[0],value[4],value[3],value[2],value[1]))
      elif save_type == 2:
        with open('ddw.csv','a+',newline='',encoding='utf-8-sig') as f:
          writer = csv.writer(f)
          #轉(zhuǎn)化為列表 存儲
          writer.writerow(list(value))
      else:
        conn = pymysql.connect(host='127.0.0.1',user='root',passwd='',db='',port=3306,charset='utf8')
        cursor = conn.cursor()
        sql = ''
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()
  #公有對象方法 執(zhí)行所有爬蟲操作
  def my_run(self,parser_type=1,save_type=1):
    my_url = self.__my_url()
    for value in my_url:
      result = self.__my_request(value,parser_type)
      self.__my_save(result,save_type)

調(diào)用爬蟲類實現(xiàn)數(shù)據(jù)獲取

if __name__ == '__main__':
  #實例化創(chuàng)建對象
  dd = DDSpider('python',0)
  #參數(shù) 解析方式 my_run(parser_type,save_type)
  # parser_type 1 利用正則 2 bs4 3 xpath 
  #存儲方式 save_type 1 txt 2 csv 3 mysql
  dd.my_run(2,1)

==總結(jié)一下: ==

1. 總體感覺正則表達(dá)式更簡便一些 , 代碼也會更簡便 , 但是正則部分相對復(fù)雜和困難
2. bs4和xpath 需要對html代碼有一定了解 , 取每條數(shù)據(jù)多個值時相對較繁瑣

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

  • Python的Flask框架及Nginx實現(xiàn)靜態(tài)文件訪問限制功能

    Python的Flask框架及Nginx實現(xiàn)靜態(tài)文件訪問限制功能

    這篇文章主要介紹了Python的Flask框架及Nginx實現(xiàn)靜態(tài)文件訪問限制功能,Nginx方面利用到了自帶的XSendfile,需要的朋友可以參考下
    2016-06-06
  • python httpx的具體使用

    python httpx的具體使用

    本文主要介紹了python httpx的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Python實現(xiàn)機器學(xué)習(xí)算法的分類

    Python實現(xiàn)機器學(xué)習(xí)算法的分類

    今天給大家整理了Python實現(xiàn)機器學(xué)習(xí)算法的分類的文章,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)的小伙伴們很有幫助,需要的朋友可以參考下
    2021-06-06
  • 基于Python編寫一個有趣的年會抽獎系統(tǒng)

    基于Python編寫一個有趣的年會抽獎系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了如何使用Python編寫一個簡易的抽獎系統(tǒng),順便幫助大家鞏固一下對Python語法和框架的理解,感興趣的小伙伴可以了解下
    2023-12-12
  • Pandas?Query方法使用深度總結(jié)

    Pandas?Query方法使用深度總結(jié)

    大多數(shù)Pandas用戶都熟悉iloc[]和loc[]索引器方法,用于檢索行和列。但是隨著檢索數(shù)據(jù)的規(guī)則變得越來越復(fù)雜,這些方法也隨之變得更加復(fù)雜而臃腫。本文將展示如何使用?query()?方法對數(shù)據(jù)框執(zhí)行查詢,感興趣的可以了解一下
    2022-07-07
  • centos7之Python3.74安裝教程

    centos7之Python3.74安裝教程

    這篇文章主要介紹了centos7之Python3.74安裝教程,本文給大家介紹的非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下
    2019-08-08
  • 解決python 在for循環(huán)并且pop數(shù)組的時候會跳過某些元素的問題

    解決python 在for循環(huán)并且pop數(shù)組的時候會跳過某些元素的問題

    這篇文章主要介紹了解決python 在for循環(huán)并且pop數(shù)組的時候會跳過某些元素的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • PyGame貪吃蛇的實現(xiàn)代碼示例

    PyGame貪吃蛇的實現(xiàn)代碼示例

    貪吃蛇是款經(jīng)典游戲,本文將帶你一步步用python語言實現(xiàn)一個貪吃蛇小游戲,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • python智聯(lián)招聘爬蟲并導(dǎo)入到excel代碼實例

    python智聯(lián)招聘爬蟲并導(dǎo)入到excel代碼實例

    這篇文章主要介紹了python智聯(lián)招聘爬蟲并導(dǎo)入到excel代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • python 解決Windows平臺上路徑有空格的問題

    python 解決Windows平臺上路徑有空格的問題

    這篇文章主要介紹了python 解決Windows平臺上路徑有空格的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11

最新評論

策勒县| 噶尔县| 旬邑县| 巫溪县| 隆回县| 太谷县| 纳雍县| 双牌县| 太原市| 鹤山市| 长治县| 九寨沟县| 化隆| 偃师市| 留坝县| 巩留县| 手机| 绥棱县| 烟台市| 新蔡县| 封开县| 吴堡县| 榆社县| 建平县| 大庆市| 海盐县| 汝阳县| 嘉祥县| 梅河口市| 闽侯县| 土默特左旗| 无棣县| 报价| 陇川县| 辽阳市| 壶关县| 台前县| 托克逊县| 噶尔县| 穆棱市| 伊川县|