python爬取淘宝商品销量信息

yipeiwu_com5年前Python爬虫

python爬取淘宝商品销量的程序,运行程序,输入想要爬取的商品关键词,在代码中的‘###'可以进一步约束商品的属性,比如某某作者的书籍,可以在###处输入作者名字,以及时期等等。最后可以得到所要商品的总销量

import requests
import bs4
import re
import json
 
def open(keywords, page):
   headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
 
   payload = {'q':keywords, 'sort':"sale-desc", 's':(page-1)*44}
   url = "https://s.taobao.com/search"
 
   res = requests.get(url, params = payload)
   return res
   
   
def get_item(res):
 
   g_page_config = re.search(r'g_page_config = (.*?);\n', res.text)
   page_config_json = json.loads(g_page_config.group(1))
   page_item = page_config_json['mods']['itemlist']['data']['auctions']
 
   result = []#整理出我们关注的信息(ID,标题,链接,售价,销量和商家)
   for each in page_item:
      dict1 = dict.fromkeys(('id','title','link','price','sale','shoper'))
      dict1['id'] = each['nid']
      dict1['title'] = each['title']
      dict1['link'] = each['detail_url']
      dict1['price'] = each['view_price']
      dict1['sale'] = each['view_sales']
      dict1['shoper'] = each['nick']
      result.append(dict1)
 
   return result
      
def count_sales(items):
   count = 0
   for each in items:
      if '###' in each['title']:#规定只取标题中‘###'的商品
         count += int(re.search(r'\d+',each['sale']).group())
         
   return count
 
def main():
 
   keywords = input("请输入搜索关键词:")#可以为各种商品名称
   length = 10#淘宝商品页数
   total = 0
   
   for each in range(length):
      res = open(keywords, each+1)
      items = get_item(res)
      total += count_sales(items)#销售总量
   print(total)
 
 
if __name__ == "__main__":
   main()

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

相关文章

python爬虫 基于requests模块的get请求实现详解

需求:爬取搜狗首页的页面数据 import requests # 1.指定url url = 'https://www.sogou.com/' # 2.发起get请求:get方法会返...

Python爬虫之xlml解析库(全面了解)

1.Xpath Xpath是一门在XML中查找信息的语言,可用来在XML文档中对元素和属性进行遍历。XQuery和xpoint都是构建于xpath表达之上 2.节点 父(parent),...

python爬虫实现教程转换成 PDF 电子书

python爬虫实现教程转换成 PDF 电子书

写爬虫似乎没有比用 Python 更合适了,Python 社区提供的爬虫工具多得让你眼花缭乱,各种拿来就可以直接用的 library 分分钟就可以写出一个爬虫出来,今天就琢磨着写一个爬虫...

python爬虫获取多页天涯帖子

今天练习了抓取多页天涯帖子,重点复习的知识包括 soup.find_all和soup.selcet两个筛选方式对应不同的参数; 希望将获取到的多个内容组合在一起返回的时候,要用...

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

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