【第三周】正则表达式、爬虫实战——python爬虫慕课笔记

文章目录

  • 第七单元 Re正则表达式
    • 正则表达式的概念
    • 正则表达式的语法
    • Re库的基本使用
      • search函数
      • match函数
      • findall函数
      • split函数
      • finditer函数
      • sub函数
    • match对象
    • re库的贪婪匹配和最小匹配
    • 小结
  • 第八单元 实例:淘宝商品比价定向爬虫
  • 第九单元 实例:股票数据定向爬虫

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第1张图片

第七单元 Re正则表达式

正则表达式的概念

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第2张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第3张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第4张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第5张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第6张图片
可以理解为:编译之前只是符合语法的单一字符串,编译后才是符合特征的正则表达式

正则表达式的语法

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第7张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第8张图片
例子:
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第9张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第10张图片
邮政编码,代表第一位是1-9,后面5位是任意数字
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第11张图片

Re库的基本使用

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第12张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第13张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第14张图片
因此,当正则表达式中包含转义符时,使用raw string类型来表示正则表达式
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第15张图片

search函数

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第16张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第17张图片
M:若字符串是一篇文章,则可以匹配每一行
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第18张图片

match函数

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第19张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第20张图片
由于match是从第一个字符开始匹配,第一个字符为B,不符合正则表达式,因此返回的match对象没有group值,因此需要判断

findall函数

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第21张图片
其返回列表类型,里面是匹配的内容
在这里插入图片描述

split函数

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第22张图片
是将不匹配是部分分割出来,maxsplit控制分割几次
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第23张图片

finditer函数

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第24张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第25张图片

sub函数

替换符合正则表达式的字符串
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第26张图片
在这里插入图片描述
对一个正则表达式在多个函数中的使用:compile
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第27张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第28张图片
regex才是正则表达式对象,可以使用对象方法,与re库的6个方法一致
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第29张图片
函数去掉第一个参数(正则表达式字符串)

match对象

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第30张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第31张图片【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第32张图片

re库的贪婪匹配和最小匹配

一个字符串中可以有多个匹配项:
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第33张图片
re库默认贪婪匹配
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第34张图片
如何使用最小匹配?加一个问号
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第35张图片
【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第36张图片

小结

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第37张图片

第八单元 实例:淘宝商品比价定向爬虫

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第38张图片
查看网页源代码可知,淘宝界面价格对应view_price
商品名称对应raw_title

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(lit,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(tit[i].split(':')[1])
            ilt.append([price,title])
    except:
        print("")

def printGoodList(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='https://s.taobao.com/search?q='+goods
    infoList=[]
    for i in range(depth):
        try:
            url=start_url+'&s='+str(44*i)
            html=getHTMLText(url)
            parsePage(infoList,html)
        except:
            continue
    printGoodList(infoList)

main()

实测已经打印不出来了,应该是界面有改版,个人没有前端知识,就不debug了

第九单元 实例:股票数据定向爬虫

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第39张图片
当前技术路线,需要我们选取将数据写在html页面中的网站
而实例中给出的获取股票列表的网站:
http://quote.eastmoney.com/stocklist.html
现在查看源代码已经获取不到内容,也就不是吧数据写在html中
而获取股票详情的页面http://gupiao.baidu.com/stock/
甚至已经不存在了
因此这个例子2021.2也不可实现QAQ
以下代码仅供参考思路

import requests
from bs4 import BeautifulSoup
import traceback
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 getStockList(lst,stockURL):
    html=getHTMLText(stockURL)
    soup=BeautifulSoup(html,'html.parser')
    a=soup.find_all('a')
    for i in a:
        try:
            href=i.attrs['href']
            lst.append(re.findall(r"[s][hz]\d{6}",href)[0])
        except:
            continue

def getStockInfo(lst,stockURL,fpath):
    for stock in lst:
        url=stockURL+stock+".html"
        html=getHTMLText(url)
        try:
            if html=="":
                continue
            infoDict={
     }
            soup=BeautifulSoup(html,'html.parser')
            stockInfo=soup.find('div',attrs={
     'class':'stock-bets'})
            
            name=stockInfo.find_all(attrs{
     'class':'bets-name'})[0]
            infoDict.update({
     '股票名称':name.text.split()[0]})

            keyList=stockInfo.find_all('dt')
            valueList=stockInfo.find_all('dd')
            for i in range(len(keyList)):
                key=keyList[i].text
                val=valueList[i].text
                infoDict[key]=val
                
            with open(fpath,'a',encoding='utf-8') as f:
                f.write(str(infoDict)+'\n')
        except:
            traceback.print_exc()#打印错误信息
            continue
            
            

def main():
    stock_list_url='http://quote.eastmoney.com/stocklist.html'
    stock_info_url='http://gupiao.baidu.com/stock/'
    output_file='D://BaiduStockInfo.txt'
    slist=[]
    getStockList(slist,stock_list_url)
    getStockInfo(slist,stock_info_url,output_file)

main()

【第三周】正则表达式、爬虫实战——python爬虫慕课笔记_第40张图片
\r能够将打印的光标移动到头部,下一次打印就会覆盖上一次打印,实现不换行的进度信息展示
idle中禁止了\r的使用,可以在命令行中实现

你可能感兴趣的:(Python爬虫慕课,python,爬虫)