Python-实现根据关键词获取网页内容

一、项目介绍

获取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标签是我们需要的内容。
Python-实现根据关键词获取网页内容_第1张图片

三、源码

# 已失效,需要登录
import requests
import re

def 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()




你可能感兴趣的:(#,python)