|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
尝试爬取淘宝商品页面价格信息,代码如下:
- 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("")
- def printGoodList(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
- printGoodList(infoList)
- main()
复制代码
输出的结果为
- RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python37-32/实战2淘宝爬取商品价格.py
- 序号 价格 商品名称
复制代码
请问各位大佬神仙geek们,是哪里出了问题呀?
在线等。
本帖最后由 chxchxkkk 于 2019-6-6 08:37 编辑
parsePage函数没有返回值,
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(infoList,html) ---》调用没有返回值的函数,所以什么也没有
except:
continue
printGoodList(infoList)
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.split(':')[1])
title = eval(tlt.split(':')[1])
ilt.append([price,title])
return ilt ---->加上返回值
|
|