爬虫学习W07-W12

re库

raw string

r’text’

功能函数

函数说明
re.search()搜索匹配正则的第一个位置
re.match()从开始位置起匹配
re.findall()搜索字符串,以列表类型返回全部能匹配的
re.split()分割,返回列表
re.finditer()搜索,返回一个匹配结构的迭代类型,每个迭代元素是match对象
re.sub()在一个字符串中替换所有匹配的自传,返回替换后的字符串

re.search(pattern,string,flags=0)

flags
re.I忽略大小写
re.M^操作符可以将每行当做匹配开始
re.S.操作符匹配所有字符(除换行外)

maxsplit超过最大分割数的剩余部分整体输出
repl替换字符串
count替换最大次数

re库的使用方法

  1. 函数式rst = re.search(r'text','text')
  2. 面向对象

pat = re.compile(r’text’)
rst = pat.search(‘text’)

match对象的属性

属性说明
.string待匹配文本
.re匹配时使用的正则
.pos开始搜索的位置
.endpos搜索文本结束的位置
方法说明
.group()获得匹配后的字符串
.start()匹配字符串在原始的开始位置
.end()匹配在原始的结束位置
.span()返回(.start(),.end())

默认贪婪匹配

最小匹配操作符

操作符说明
*?前一个字符0或无限
+?前一个字符一次或无限
??0次或一次
{m,n}?m至n次,包含n

淘宝商品

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]))
    print("")

def main():
    goods="眼镜"
    depth=2
    start_url="https://s.taobao.com/search?q="+goods
    infoList=[]
    for i in range(depth):
        try:
            url=start_url +"&s="+str(44*i)
            headers={
                "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
                "cookie":""#一定得登录后用ctrlf搜索商品复制
            }
            html=requests.get(url,headers=headers)
            print(html.text)
            parsePage(infoList,html.text)
        except:
            continue
    printGoodsList(infoList)
main()

股票定向爬虫

def getFundList(lst, fundURL):

    html = getHTMLText(fundURL)

    soup = BeautifulSoup(html, 'html.parser')

    a = soup.find_all('tr')

    for i in a:

        try:

            id = i.attrs['id']

            lst.append(re.findall(r"[tr]\d{6}", id)[0])

        except:

            continue

 

def getFundInofo(lst, fundURL, fpath):

    for fund in lst:

        url = fundURL + fund[1:] + ".html"

        html = getHTMLText(url)

        try:

            if html == '':

                continue

            infoDict = {}

            soup = BeautifulSoup(html, 'html.parser')

            fundInfo = soup.find('div', attrs={'class': "merchandiseDetail"})

            name = fundInfo.find_all(attrs={'class': "fundDetail-tit"})[0]

            infoDict.update({'基金名称': name.text.split()[0]})

 

            keyList = fundInfo.find_all("dt")

            valueList = fundInfo.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():

    fund_list_url = "https://fund.eastmoney.com/fund.html#os_0;isall_0;ft_;pt_1"

    fund_info_url = "https://fund.eastmoney.com/"

    output_file = 'D://Fundinfo.txt'

    slist = []

    getFundList(slist, fund_list_url)

    getFundInofo(slist, fund_info_url, output_file)

scrapy框架

5+2结构
engine:
控制所有模块之间的数据流
根据条件触发事件
不需要用户修改

downloader:
根据请求下载网页
不需要用户修改

scheduler:
对所有爬取请求进行调度管理
不需要用户修改

*downloader middleware:*进行用户可配置的控制
功能:修改、丢弃、新增请求或响应
用户可以编写配置代码

spider

  • 解析downloader返回的响应(response)
  • 产生爬取项(scraped item)
  • 产生额外的爬取请求(request)
  • 需要用户编写配置代码

item pipelines

  • 以流水线方式处理spider产生的爬取项
  • 由一组操作顺序组成,类似流水线,每个操作是一个item pipeline类型
  • 可能的操作包括:清理,检验和查重爬取项中的HTML数据、将数据存储到数据库
  • 需要用户编写配置代码

spider middleware目的:对请求和爬取项的再处理
功能:修改、丢弃、新增请求或爬取项
用户可以编写配置代码

常用命令

scrapy <command> [options] [args]

命令说明格式
startproject创建一个新工程scrapy startproject <name>[dir]
genspider创建一个爬虫scrapy genspider [options]<name>[domain]
settings获得爬虫配置信息scrapy settings [options]
crawl运行一个爬虫scrapy crawl<spider>
list列出工程中所有爬虫scrapy list
shell启动URL调试命令行scrapy shell [url]

yield生成器

  • 一个不断产生值的函数
  • 包含yield语句的函数是一个生成器
  • 生成器每次产生一个值(yield语句),函数被冻结,被唤醒后再产生一个值
def gen(n):
	for i in range(n):
		yield i**2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值