本文共 1520 字,大约阅读时间需要 5 分钟。
获取TB网页的一些信息(仅进行教育目的)
比如我们要通过关键字获取TB界面上的一些信息。 通过确认可以发现请求为:https://s.taobao.com/search?q=书包&s=0 #q代表关键字,显示第一页https://s.taobao.com/search?q=书包&s=44 #显示第二页,每一个44个
结构设计:
使用的解析方法有多种,一种使用BeatifulSoup库,一种使用正则表达式直接匹配出来。我们这里使用正则表达式。
通过查看源码可以看到,view_price和raw_title标签是我们需要的内容。# 已失效,需要登录import requestsimport redef getHTMLText(url): try: r = requests.get(url, timeout = 30) r.raise_for_status() r.encoding = r.apparent_encoding #防止中文乱码 print(r.text) 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 printGoodsList(ilt): print(ilt) tplt = "{:4}\t{:8}\t{:16}" print(tplt.format("序号", "价格", "商品名称")) count = 0 for g in ilt: count = coount +1 print(tplt.format(count, g[0], g[1]))def main(): goods = '书包' depth = 1 #搜索两页,每页44个商品 start_url = 'https://s.taobao.com/search?q=' + goods infoList = [] for i in range(depth): try: url = start_url + '&s=' + str(44*i) print(url) html = getHTMLText(url) parsePage(infoList, html) except: continue printGoodsList(infoList)main()
转载地址:http://guhpn.baihongyu.com/