python定向爬取淘宝商品价格

yipeiwu_com6年前Python爬虫

python爬虫学习之定向爬取淘宝商品价格,供大家参考,具体内容如下

import requests
import re

def getHTMLText(url):
  try:
    r = requests.get(url, timeout=30)
    r.raise_for_status() #如果发送了一个失败请求(非200响应),#我们可以通过 Response.raise_for_status() 来抛出异常:
    r.encoding= r.apparent_encoding
    return r.text
  except:
    return ""

def parsePage(ilt,html):
  try:
    plt = re.findall(r'\"view_price\"\:\"[\d\.]*?\"',html) #正则表达式来匹配 "view_price":"\d\."类型的字符串
    tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
#正则表达式来匹配 "raw_title":".*?"类型的字符串,.*?是任意字符的最小匹配
    for i in range(len(plt)):
      price = eval(plt[i].split(':')[1])
      title = eval(tlt[i].split(':')[1])
      ilt.append([price,title])
  except:
    print ("")


def PrintGoodsList(ilt):
  tplt = "{:4}\t{:8}\t{:16}"
  print (tplt.format("序号","价格","商品名称"))
  count = 0
  for g in ilt:
    count = count + 1
    print (tplt.format(count,g[0],g[1]))
def main():
  goods = '书包'
  depth = 2
  start_url = 'https://s.taobao.com/search?q=' + goods
  infoList=[]
  for i in range(depth):
    try:
      url = start_url + '&s=' + str(44*i)
      html= getHTMLText(url)
      parsePage(infoList,html)
    except:
      continue

  PrintGoodsList(infoList)

main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python&MongoDB爬取图书馆借阅记录

python&MongoDB爬取图书馆借阅记录

直接上需求和代码 首先是需要爬取的链接和网页:http://211.81.31.34/uhtbin/cgisirsi/x/0/0/57/49?user_id=LIBSCI_ENGI&pa...

Python爬虫包BeautifulSoup简介与安装(一)

先发官方文档的地址:官方文档 学习使用的书籍是Python网络数据采集(Ryan Mitchell著),大约是一些笔记的整理。 Beautiful Soup的简介 简单来说,Beauti...

python实现知乎高颜值图片爬取

导入相关包 import time import pydash import base64 import requests from lxml import etree from...

python爬虫_实现校园网自动重连脚本的教程

python爬虫_实现校园网自动重连脚本的教程

一、背景 最近学校校园网不知道是什么情况,总出现掉线的情况。每次掉线都需要我手动打开web浏览器重新进行账号密码输入,重新进行登录。系统的问题我没办法解决,但是可以写一个简单的pytho...

python爬虫之urllib库常用方法用法总结大全

Urllib 官方文档地址:https://docs.python.org/3/library/urllib.html urllib提供了一系列用于操作URL的功能。 本文主要介绍的是...