淘宝定向爬取-MOOC学习笔记

  在学习了request库之后有跟着视频学习过 中国最好大学排名 的爬取,不过很尴尬的是,我的返回是个空值。??!!??

  在自己尝试了N次以后还是不清楚问题出在哪里,这就是水平不过的体现了,所以这次我又接下去学习了 淘宝定向爬取 ,皇天不负有心人,这次居然一次就成功了,我感谢天感谢地,感谢UP主!

  虽然还有很多不清楚的地方,代码也不能够写得尽善尽美,但是能够有一丢丢的成果,那终归是要努力的。

 1 import requests
 2 import re
 3 
 4 def getHTMLText(url):
 5     try:
 6         r = requests.get(url, timeout = 30)
 7         r.raise_for_status()
 8         r.encoding = r.apparent_encoding
 9         return r.text
10     except:
11         return ""
12     
13     # 关键
14 def parsePage(ilt, html):
15     try:
16         plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)   # 价格信息
17         tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)       # 商品名称
18         for i in range(len(plt)):
19             price = eval(plt[i].split(':')[1])
20             title = eval(tlt[i].split(':')[1])
21             ilt.append([price, title])
22     except:
23         print ('')
24 
25 def printGoodsList(ilt):
26     tplt = "{:4}\t{:8}\t{:16}"  #规定位置 第一个长度为4 二为8
27     print(tplt.format("序号", "价格", "商品名称"))   # 打印表头
28     count = 0
29     for g in ilt:
30         count = count + 1
31         print(tplt.format(count, g[0], g[1]))
32         
33 def main():
34     goods = '魅族pro6s手机壳'
35     depth = 2
36     start_url = 'https://s.taobao.com/search?q=' + goods
37     infoList = []
38     for i in range(depth):
39         try:
40             url = start_url + '&s=' + str(44*i)
41             html = getHTMLText(url)
42             parsePage(infoList, html)
43         except:
44             continue
45     printGoodsList(infoList)
46 
47 main()
淘宝定向爬取

猜你喜欢

转载自www.cnblogs.com/canvas2018/p/9130632.html