利用python爬取什么值得买上面的爆料信息

来源:互联网 发布:淘宝买家具组装很烦 编辑:程序博客网 时间:2024/04/30 05:50

1、目的:主要到什么值得买网站上采集由用户爆料的信息并做分析。

2、环境:python 3.4.4 

所需module  request、BeautifulSoup、mysql.connector等详情看代码。

数据库:mysql

3、根据分析什么值得买上展现的商品信息,得知当向后台发送http://www.smzdm.com/jingxuan/json_more?timesort=1502089661&filter=s0f0t0b0d0r0p0 时,会得到后台返回的json数据。注意timesort是每个商品都有的,举个例子,比如精选模块展现的商品是1~10个商品,那么取第10个商品的timesort向后台发送请求,即可得到后面二十个商品的详情信息,以此类推即可。

4、解析数据,存入数据库

5、代码如下

#encoding :utf-8
import urllib.request
import socket
import os
import sys
import re
from bs4 import BeautifulSoup
import mysql.connector


def getHtml(timeout):
  weburl='http://www.smzdm.com/jingxuan/json_more?timesort='+timeout+"&filter=s0f0t0b0d0r0p0"
  webheader={'Connection': 'Keep-Alive','Accept': 'text/html, application/xhtml+xml, */*','Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3','User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0','Host': 'www.smzdm.com'}
  req=urllib.request.Request(url=weburl,headers=webheader)
  webpage=urllib.request.urlopen(req)
  contentBytes=webpage.read()
  str_=str(contentBytes.decode("unicode_escape"))#可直接获取相应的中文
  return str_
  i=0
def getValue(os):
  
  str_=getHtml(os)#初始页面值
  str_unworthy=re.findall(r'(?<="article_unworthy":").+?(?=",)',str_,re.M)
  str_title=re.findall(r'(?<="article_title":").+?(?=",)',str_,re.M)
  str_worthy=re.findall(r'(?<="article_worthy":").+?(?=",)',str_,re.M)
  str_comment=re.findall(r'(?<="article_comment":").+?(?=",)',str_,re.M)
  str_collect=re.findall(r'(?<="article_collection":").+?(?=",)',str_,re.M) 
  #根据timesort来不断循环所要的结果
  str_timesort=re.findall(r'(?<="article_timesort":)\d+',str_,re.M)
  print(str_timesort)
  for x in range(0,len(str_title)):   
  # tit=''+str(str_title[x])
  # print('------')
  # print(isinstance(tit,str))
  #print(str_title[x])
  str_ti=str(str_title[x])
  #str_2=""
  if(len(str_ti)>200):str_ti=str_ti[0:150]
  getDB(str_ti,str(str_worthy[x]),str(str_unworthy[x]),str(str_comment[x]),str(str_collect[x]))
  #s=u""+tit  
  #print(str_title)
  index=len(str_timesort)-1  #p10001 1449209933
  if('1449209933' in str_timesort):#该timesort指只获取到该页面中的商品即可,不再继续往下循环了 。比如:你需获取p1000中的商品,p1001的商品不需要了,则取该页面中随便一个商品的数量,否则会继续递归循环走下去。
   print('--------end----------')  
  else:
    print (index)
    return getValue(str_timesort[index])
     # print (str_timesort[index])
# for x in range(1,100):
# 链接数据库
def getDB(title,good,bad,comment,collect):
  user = 'root'
  pwd  = 'root321'
  host = '127.0.0.1'
  db   = 'mydata'
  cnx = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
  agr1='不好'
  sql="insert into db_test(type,title,good,bad,comment,collect) values('国内优惠','"+title+"','"+good+"','"+bad+"','"+comment+"','"+collect+"')"
  cursor=cnx.cursor()
  try:
  cursor.execute(sql)
  except Exception:print('有异常')
  cnx.commit()
  cursor.close()
  cnx.close()
if __name__ == '__main__':
  print('---------star-------')
  getValue('1502089661')
 


存入数据库:


原创粉丝点击