欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python爬蟲爬取、解析數據操作示例

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

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

爬蟲 當當網 http://search.dangdang.com/?key=python&act=input&page_index=1

  1. 獲取書籍相關信息
  2. 面向對象思想
  3. 利用不同解析方式和存儲方式

引用相關庫

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):
  #對象屬性 參數 關鍵字 頁數
  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
  
  #私有對象方法 請求數據
  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
    
  #私有對象方法 解析數據 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標簽
          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標簽
          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
  
  #私有對象方法 存儲數據 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)
          #轉化為列表 存儲
          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)

調用爬蟲類實現(xiàn)數據獲取

if __name__ == '__main__':
  #實例化創(chuàng)建對象
  dd = DDSpider('python',0)
  #參數 解析方式 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)

==總結一下: ==

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

更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總

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

相關文章

  • Scrapy爬蟲多線程導致抓取錯亂的問題解決

    Scrapy爬蟲多線程導致抓取錯亂的問題解決

    本文針對Scrapy爬蟲多線程導致抓取錯亂的問題進行了深入分析,并提出了相應的解決方案,具有一定的參考價值,感興趣的可以了解一下
    2023-11-11
  • Python實現(xiàn)打包成庫供別的模塊調用

    Python實現(xiàn)打包成庫供別的模塊調用

    這篇文章主要介紹了Python實現(xiàn)打包成庫供別的模塊調用,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • Python3之亂碼\xe6\x97\xa0\xe6\xb3\x95處理方式

    Python3之亂碼\xe6\x97\xa0\xe6\xb3\x95處理方式

    這篇文章主要介紹了Python3之亂碼\xe6\x97\xa0\xe6\xb3\x95處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python實現(xiàn)郵件發(fā)送功能

    python實現(xiàn)郵件發(fā)送功能

    這篇文章主要為大家詳細介紹了python實現(xiàn)郵件發(fā)送功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • pytz格式化北京時間多出6分鐘問題的解決方法

    pytz格式化北京時間多出6分鐘問題的解決方法

    這篇文章主要給大家介紹了關于pytz格式化北京時間多出6分鐘問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Python具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-06-06
  • 淺談Python處理PDF的方法

    淺談Python處理PDF的方法

    這篇文章主要介紹了Python處理PDF的兩種方法代碼示例,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • Python的Urllib庫的基本使用教程

    Python的Urllib庫的基本使用教程

    這篇文章主要介紹了Python的Urllib庫的基本使用教程,是用Python編寫爬蟲的必備知識,需要的朋友可以參考下
    2015-04-04
  • Python解決雞兔同籠問題的方法

    Python解決雞兔同籠問題的方法

    這篇文章主要介紹了Python解決雞兔同籠問題的方法,分析了雞兔同籠問題的原理與解決思路,并給出了Python實現(xiàn)的代碼,非常具有參考借鑒價值,需要的朋友可以參考下
    2014-12-12
  • 一文詳細NumPy中np.zeros的使用

    一文詳細NumPy中np.zeros的使用

    np.zeros是NumPy庫中一個非常實用的函數,用于快速創(chuàng)建指定形狀和大小的全零數組,本文主要介紹了NumPy中np.zeros的使用,感興趣的可以了解一下
    2024-03-03
  • python 類的繼承 實例方法.靜態(tài)方法.類方法的代碼解析

    python 類的繼承 實例方法.靜態(tài)方法.類方法的代碼解析

    這篇文章主要介紹了python 類的繼承 實例方法.靜態(tài)方法.類方法的代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08

最新評論