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使用tornado实现简单爬虫

本文实例为大家分享了python使用tornado实现简单爬虫的具体代码,供大家参考,具体内容如下 代码在官方文档的示例代码中有,但是作为一个tornado新手来说阅读起来还是有点困难的...

Python实现爬取需要登录的网站完整示例

本文实例讲述了Python爬取需要登录的网站实现方法。分享给大家供大家参考,具体如下: import requests from lxml import html # 创建 sess...

三个python爬虫项目实例代码

这篇文章主要介绍了三个python爬虫项目实例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 爬取内涵段子: #encodi...

python编写网页爬虫脚本并实现APScheduler调度

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

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

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