亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python3爬取淘寶信息代碼分析

 更新時(shí)間:2018年02月10日 14:13:15   作者:追心  
本篇文章通過代碼實(shí)例給大家分享了python3爬取淘寶信息的過程以及實(shí)例分析,對此有興趣的朋友學(xué)習(xí)下。
# encoding:utf-8
import re # 使用正則 匹配想要的數(shù)據(jù)
import requests # 使用requests得到網(wǎng)頁源碼

這個(gè)函數(shù)是用來得到源碼

# 得到主函數(shù)傳入的鏈接
def getHtmlText(url):
  try: # 異常處理
    # 得到你傳入的URL鏈接 設(shè)置超時(shí)時(shí)間3秒
    r = requests.get(url, timeout=3)
    # 判斷它的http狀態(tài)碼
    r.raise_for_status()
    # 設(shè)置它的編碼 encoding是設(shè)置它的頭部編碼 apparent_encoding是從返回網(wǎng)頁中分析它的編碼格式
    r.encoding = r.apparent_encoding
    # 返回源代碼
    return r.text
  except: # 發(fā)生異常返回空
    return ''

這個(gè)函數(shù)使用來解析你的源代碼 獲取你想要的數(shù)據(jù)

# 解析你的網(wǎng)頁信息
def parsePage(ilt, html):
  # 異常處理
  try:
    # 找到書包的價(jià)格
    plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
    # 找到書包的名稱
    tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)
    # 找到書包的地址
    add = re.findall(r'\"item_loc\"\:\".*?\"', html)
    # 找到書包的圖片鏈接
    img = re.findall(r'\"pic_url\"\:\".*?\"', html)
    # 得到這個(gè)內(nèi)容放入主函數(shù)中的列表
    for i in range(len(plt)):
      price = eval(plt[i].split(':')[1])
      title = eval(tlt[i].split(':')[1])
      address = eval(add[i].split(':')[1])
      imgs = eval(img[i].split(':')[1])  
      ilt.append([price, title, address, imgs])
  except: # 放生異常輸出空字符串
    print('')
# 得到主函數(shù)傳入的列表
def printGoodsList(ilt):
  # 每個(gè)列之間用tplt的放是隔開
  tplt = '{:4}\t{:8}\t{:16}\t{:32}'
  # 這個(gè)是整個(gè)的標(biāo)題
  print(tplt.format('序號', '價(jià)格', '商品名稱','地址', '圖片地址'))
  count = 0 # 統(tǒng)計(jì)有多少的序號
  for g in ilt:
    count = count + 1 # 循環(huán)一遍加一
    print(tplt.format(count, g[0], g[1], g[2]), g[3]) # 輸出你得到的數(shù)據(jù)
# 定義主函數(shù) main
def main():
  goods = '書包' # 你要搜索的東西
  depth = 2 # 你想要得到幾頁的東西
  start_url = 'https://s.taobao.com/search?q=' + goods # 你搜索的網(wǎng)址加上你的搜索東西
  infoList = [] # 自定義的空列表用來存放你的到的數(shù)據(jù)
  for i in range(depth): # 循環(huán)你的頁數(shù)
    try: # 異常處理
      url = start_url + '&s' + str(44 * i) # 得到你的網(wǎng)址
      html = getHtmlText(url) # 得到url傳入到你要得到url的函數(shù)中
      parsePage(infoList, html) # 得到你的html源碼 放入解析的網(wǎng)頁中
    except: # 發(fā)生異常跳過
      continue
  # 把列表中的數(shù)據(jù)放入解析的函數(shù)中
  printGoodsList(infoList)
# 代碼調(diào)試片段
if __name__ == '__main__':
  main() # 調(diào)用主函數(shù)

以上就是經(jīng)過小編測試過的用python3爬取淘寶信息的代碼,大家測試后如果還有任何不明白的地方可以在下方的留言區(qū)討論。

相關(guān)文章

最新評論