import requests
import re
def getHTMLText(url):
try:
r= requests.get(url,timeout=30)
r.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)
tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
ilt.append([price,title])
except:
print("F")
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()
这段代码在过去是可以爬取淘宝商品信息,但是因为淘宝的反扒技术升级,便不能让你大摇大摆地进出自如了。
此外也可以借助采集实现采集
// ==UserScript==// @name JD
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://item.jd.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict'
// Your code here...
var divObj=document.createElement("input")
divObj.type="button"
divObj.value='获取抓取内容'
divObj.style.marginTop="20px"
divObj.style.marginBottom="20px"
divObj.style.marginLeft="50px"
var first=document.body.firstChild
document.body.insertBefore(divObj,first)
var result={}
divObj.onclick=function(){
//获取价格
if(document.getElementById("jd-price")){
var priceDiv=document.getElementById("jd-price")
var price = priceDiv.innerText
price = price.substr(1)
}else if(document.getElementById("price")){
var pricePri=document.getElementById("price")
var priceDiv=pricePri.firstElementChild
var price = priceDiv.innerText
}else if(document.getElementsByClassName("price")[0]){
var priceClass=document.getElementsByClassName("price")
var priceDiv=priceClass[0]
var price = priceDiv.innerText
}
result.price=price
}