Python爬取数据(二)

一.example2包下的

1.re模块的compile函数使用

python 复制代码
import re

pattern=re.compile(r'\d+')
print(pattern)

2.match的方法使用

python 复制代码
import re
pattern=re.compile(r'\d+')
# m1=pattern.match('one123twothree345four')
#参数2:指定起始位置(包含),参数3:终止位置(包含),注意匹配一次成功后结束
m1=pattern.match('one123twothree345four',3,7)
print(m1.group())

3.search方法的使用

python 复制代码
import re
pattern=re.compile(r'\d+')
m1=pattern.search('one123twothree345four')
print(m1.group())

4.findall方法的使用

python 复制代码
import re
pattern=re.compile(r'\d+')



result=pattern.findall('hello 123 world 456')
print(result)

5.split方法的使用

python 复制代码
import re

str1='a,b,c'
print(str1.split(','))

str2='a,b;;c,d'
pattern=re.compile(r"[\s\,\;]+")
print(pattern.split(str2))

6.sub方法的使用

python 复制代码
import re
string='<h1 class="test1">HelloWorld</h1>'

pattern=re.compile(r'\d')
print(pattern.sub('2',string))
print(pattern.sub('2',string,1))

pattern=re.compile('<(.\\d)\\sclass="(?P<classname>.*?)">.*?</(\\1)>')
print(pattern.search(string).group(3))

def fun(m):
    return 'after sub'+m.group('classname')
print(pattern.sub(fun, string))

7.贪婪匹配

python 复制代码
import re
string='<h1 class="test1">HelloWorld</h1>'
#贪婪匹配
pattern=re.compile(r'<.\d\sclass=.*>')
print(pattern.search(string).group())
#关闭贪婪匹配
pattern=re.compile(r'<.\d\sclass=.*?>')
print(pattern.search(string).group())

8.综合案例

python 复制代码
import requests
import re
def handle_detail_re(content):
    #re.S表示全文匹配
    # item_search=re.compile('ts_solgcont_title">.*?</div>\r\n\t</div>',re.S)
    item_search = re.compile('ts_solgcont_title">.*?<div class="ts_solgcont_bot">.*?</div>', re.S)
    #获取每一条图书的数据
    all_item=item_search.findall(content)
    #匹配书名
    title_search=re.compile('target="_blank">(.*?)</a>')
    #匹配作者
    author_search=re.compile('<p>作者(.*?)</p>')
    for item in all_item:
        print({
            "title":title_search.search(item).group(1),
            "author":author_search.search(item).group(1),
        })


def main():
    header={
        "User-Agent":"Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 CrKey/1.54.250320 Edg/135.0.0.0"
    }

    booktype=['java','python','c']
    for key in booktype:
        url='http://www.cmpedu.com/so.htm?&KEY={}'.format(key)
        response=requests.get(url,headers=header)
        handle_detail_re(response.text)

if __name__ == '__main__':
    main()

三.example3下的

安装beautifulsoup4的指令:pip3 install beautifulsoup4

beautifulsoup4:Beautiful Soup(bs4)是一个用于从HTML或XML文件中提取数据的Python库。

1.获取节点

python 复制代码
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p >
<p class="story">Once upon a time there were three little sisters; and their names were
<!-- Elsie -->,
 and
;
and they lived at the bottom of a well.</p >
<p class="story">...</p >
"""
#参数1:html代码片段
# 参数2:解析器
soup=BeautifulSoup(html,'lxml')
#获得标题
print(soup.title)
#获得头标记
print(soup.head)
#获得体标记
print(soup.body)
#获得标题元素内容
print(soup.title.string)
#获得标记名称
print(soup.title.name)
#默认的模式下只能匹配第一个节点,其他节点会被忽略
print(soup.p)
相关推荐
Echo缘4 小时前
嵌入式系统C语言资源分类与内存分布分析
c语言·开发语言
JaneConan4 小时前
鸿蒙 ArkUI 深水区:@Watch 和 @Observed,状态变了「自动跑」+ 嵌套对象「深层重绘」
开发语言·后端·ui·harmonyos
赤水无泪4 小时前
qt中图标、名称的设置方式
开发语言·qt
王莎莎-MinerU4 小时前
MCP 解决的是工具接入,科研 Agent 还缺的是科学证据接口标准化
开发语言·网络·人工智能·深度学习·pdf·c#·php
橘子海全栈攻城狮4 小时前
【最新源码】基于SpringBoot + Vue的超市管理系统的设计与实现D002
java·开发语言·vue.js·spring boot·后端·spring
在水一缸5 小时前
深入浅出 Catch2:现代 C++ 测试框架的优雅实践
开发语言·c++·单元测试·log4j·测试框架·catch2
AC赳赳老秦5 小时前
OpenClaw 采集任务日志审计:全程记录采集行为,满足合规溯源与企业审计要求
java·大数据·python·数据挖掘·数据分析·php·openclaw
-银雾鸢尾-5 小时前
C#中Object类内的方法
开发语言·c#
huangdong_5 小时前
电商图片下载工具横向对比深度评测:固乔、FATKUN、图快、当图、淘蛙、存图宝七款工具全面解析
python
浮江雾5 小时前
Flutter第十节-----Flutter布局与组件全解析
android·开发语言·前端·学习·flutter·入门