python爬虫实战练手——————淘宝网站的爬取

python爬虫是很好的数据分析手段,可以进行爬虫程序来进行爬取网站。下面是淘宝的爬取

淘宝搜索书包,然后得到以下的界面,

注意到下面的分页,可以通过进行分页的改变来进行多页数据的爬取。


爬取多页。



这里用到了和重要的re库 也就是正则表达式库,通过正则表达来进行数据搜索         

下面是源代码

#CrowTaobaoPrice.py
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 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 = 3
    start_url = 'http://s.taobao.com/search?q=' + goods#找到起始页的url链接
    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()

运行结果


最后一页




发布了13 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_38198952/article/details/79857799