第九天学习python

爬虫学习(四)
前面学习了requests库和beautifulsoup库
现在学习正则表达式
正则表达式使用来简洁表达字符串的表达式,一行胜千言。
正则表达式:
1.通用的字符串表达框架
2.简洁表达一串字符串
3.针对字符串表达的简洁和特征的方法
4.判断字符串特征归属
正则表达式在文本中特别常用:
1.表达文本类型(病毒.入侵)
2.同时查找或替换一组字符串
3.匹配字符串的全部部分
正则表达式的使用:
编译:将符合正则表达式语法的字符串转换成正则表达式
下面介绍正则表达式的相关符号
这里写图片描述
这里写图片描述
下面介绍re库
这里写图片描述
下面采用示例介绍:
目标:获取淘宝搜索信息,提取商品名称和价格
理解:淘宝搜索接口翻页处理

import requests
import bs4
import re
def getHTMLText(url):
    try:
        r=requests.get(url)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return ""
def parsePage(ilt,html):
    try:
        plt=re.findall(r'\"price\"\:\"[\d\.]*\"',html)
        tlt=re.findall(r'\"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 printGoddsList(ilt):
    tplt="{:4}\t{:8}\t{:16}\t"
    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
    url="https://s.taobao.com/scarch?q="+goods
    infoList=[]
    for i in range(depth):
        try:
            url=url+'&s='+str(44*i)
            html=getHTMLText(url)
            parsePage(infoList,html)
        except:
            continue
    printGoddsList(infoList)
main()

猜你喜欢

转载自blog.csdn.net/qq_40594554/article/details/81413605