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编写网页爬虫脚本并实现APScheduler调度

前段时间自学了python,作为新手就想着自己写个东西能练习一下,了解到python编写爬虫脚本非常方便,且最近又学习了MongoDB相关的知识,万事具备只欠东风。 程序的需求是这样的,...

python3之微信文章爬虫实例讲解

前提: python3.4 windows 作用:通过搜狗的微信搜索接口http://weixin.sogou.com/来搜索相关微信文章,并将标题及相关链接导入Excel表格中 说明:...

python爬取网站数据保存使用的方法

编码问题因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这个机会算是彻底搞清楚了。问题要从文字的编码讲起。原本的英文编码只有0~255,刚好是8位1个字节。为了表示各种不同的语言,自...

使用selenium和pyquery爬取京东商品列表过程解析

使用selenium和pyquery爬取京东商品列表过程解析

今天一起学起使用selenium和pyquery爬取京东的商品列表。本文的所有代码是在pycharm IDE中完成的,操作系统window 10。 1、准备工作 安装pyquery和s...

windows7 32、64位下python爬虫框架scrapy环境的搭建方法

windows7 32、64位下python爬虫框架scrapy环境的搭建方法

适用于python 2.7 64位安装 一、操作系统:WIN7 64位 二、python版本:2.7 64位(scrapy目前不支持3.x) 不确定位数的,看图 三、安装相关软件(可以...