首先要连接自己的数据库

import pymysql
import requests
#需要导入模块
db = pymysql.connect('localhost', 'root', '*********', 'mysql')#第三个是数据库密码,第四个是数据库名称
print("数据库连接成功!")
print("---------------------------------------------------")
r = requests.get("https://python123.io/ws/demo.html")#获取网页源代码
print(r.text)

几个基本操作

r = requests.get("https://python123.io/ws/demo.html")#获取网页源代码

print(r)#输出该网页请求是否成功,成功输出<Response []>

print(r.text)# 以文本形式输出网页源代码(格式和网页源代码一样)

print(r.content)#以二进制形式输出源代码(没有换行和空格)

print(r.encoding)# 输出网页编码方式

print(r.apparent_encoding)#和r.encoding功能相同,但更为精准

print(r.status_code)# 打印状态码, HTTP请求的返回状态,200表示连接成功,404表示失败

print(r.raise_for_status())# 若正常捕获网页内容,输出 None表示无异常

import re库

一、re.search(匹配规则,要匹配的字符串名称)

功能:扫描整个字符串返回第一个成功匹配的结果

result.group()获取匹配的结果
result.span()获去匹配字符串的长度范围

re.group(1)获取第一个括号中匹配的结果

import pymysql
import requests
#需要导入模块
db = pymysql.connect('localhost', 'root', '********', 'mysql')#第三个是数据库密码,第四个是数据库名称
print("数据库连接成功!")
print("---------------------------------------------------")
r = requests.get("https://python123.io/ws/demo.html")#获取网页源代码 import re
def get_text(url):#函数
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
print("-------------1-------------")
print(get_text('https://python123.io/ws/demo.html'))#输出网页源代码 demo = get_text('https://python123.io/ws/demo.html')#类似于数组赋值
#demo类似于一个数组名字
result = re.search('Th.*?ge', demo)#赋值
print("-------------2-------------")
print(result)#输出匹配字符串的长度范围和匹配的结果
print("-------------3-------------")
print(result.group())#只输出获取匹配的结果
print("-------------4-------------")
print(result.span())#输出获取匹配字符串的长度范围

输出

--------------------------
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
--------------------------
<re.Match object; span=(, ), match='This is a python demo page'>
--------------------------
This is a python demo page
--------------------------
(, )
--------------------------
['<p class="title"><b>The demo python introduces several python courses.</b></p>', '<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>'] Process finished with exit code

二、re.match(匹配规则,要匹配的字符串名称,匹配成功返回值)

功能:re.match()功能和re.search()一样,但是强调从字符串的起始位置匹配一个模式,如果不是起始位置匹配的话,match()就会返回None

一般使用re.search(),不用re.match()
语法格式:
re.match(pattern,string,flags=0)

三、re.findall(匹配规则,要匹配的字符串名称,re.s)---------re.s是输出回车换行,匹配到一个结果,输出一个换行

功能:搜索字符串,以列表(list)的形式返回全部能匹配的子串-------->print(result)

import re

html = '''<div id="songs-list">
<h2 class="title">经典老歌</h2>
<p class="introduction">
经典老歌列表
</p>
<ul id="list" class="list-group">
<li data-view="">一路上有你</li>
<li data-view="">
<a href="/2.mp3" singer="任贤齐">沧海一声笑</a>
</li>
<li data-view="" class="active">
<a href="/3.mp3" singer="齐秦">往事随风</a>
</li>
<li data-view=""><a href="/4.mp3" singer="beyond">光辉岁月</a></li>
<li data-view=""><a href="/5.mp3" singer="陈慧琳">记事本</a></li>
<li data-view="">
<a href="/6.mp3" singer="邓丽君">但愿人长久</a>
</li>
</ul>
</div>''' results = re.findall('<li.*?href="(.*?)".*?singer="(.*?)">(.*?)</a>', html, re.S) print(results)#不换行输出所有匹配的内容 print(type(results))#type(results)返回results的数据类型(列表list)
for result in results:
print(result)#以列表形式输出所有匹配内容,包括括号
print(result[], result[], result[])#以列表形式依次返回 括号内 匹配的内容,不包括括号

输出结果

[('/2.mp3', '任贤齐', '沧海一声笑'), ('/3.mp3', '齐秦', '往事随风'), ('/4.mp3', 'beyond', '光辉岁月'), ('/5.mp3', '陈慧琳', '记事本'), ('/6.mp3', '邓丽君', '但愿人长久')]
<class 'list'>
('/2.mp3', '任贤齐', '沧海一声笑')
/.mp3 任贤齐 沧海一声笑
('/3.mp3', '齐秦', '往事随风')
/.mp3 齐秦 往事随风
('/4.mp3', 'beyond', '光辉岁月')
/.mp3 beyond 光辉岁月
('/5.mp3', '陈慧琳', '记事本')
/.mp3 陈慧琳 记事本
('/6.mp3', '邓丽君', '但愿人长久')
/.mp3 邓丽君 但愿人长久
[Finished in .1s]

几种匹配规则:

1、泛匹配

^:开始匹配标志

$:匹配结束标志

import re

content= "hello 123 4567 World_This is a regex Demo"
result = re.match("^hello.*Demo$",content)
print(result)
print(result.group())
print(result.span())

输出

<re.Match object; span=(, ), match='hello 123 4567 World_This is a regex Demo'>
hello World_This is a regex Demo
(, )
[Finished in .1s]

2、目标匹配

如果为了匹配字符串中具体的目标,则需要通过()括起来,()内就是要匹配输出的内容:

import re
content= "hello 1234567 World_This is a regex Demo"
result = re.match('^hello\s(\d+)\sWorld.*Demo$',content)
print(result)
print(result.group())
print(result.group())
print(result.span())

输出

<re.Match object; span=(, ), match='hello 1234567 World_This is a regex Demo'>
hello World_This is a regex Demo (, )
[Finished in .1s]

3、贪婪匹配

.* :尽可能多的匹配非目标字符,将输出目标字符长度匹配到最小

.*? :尽可能少的匹配非目标字符,将输出目标字符长度匹配到最大

注:按目标类型分界

.* :

import re

content= "hello 1234567 World_This is a regex Demo"
result= re.match('^hello.*(\d+).*Demo',content)
print(result)
print(result.group())

输出

<re.Match object; span=(, ), match='hello 1234567 World_This is a regex Demo'>

[Finished in .1s]

.*? :

import re

content= "hello 1234567 World_This is a regex Demo"
result= re.match('^hello.*?(\d+).*Demo',content)
print(result)
print(result.group())

输出

<re.Match object; span=(, ), match='hello 1234567 World_This is a regex Demo'>
]
[Finished in .1s

4、常规匹配(比较繁琐,不常用)

import re

content= "hello 123 4567 World_This is a regex Demo"
result = re.match('^hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$',content)
print(result)#输出源代码
print(result.group())#输出匹配内容
print(result.span())#输出匹配代码的长度

输出

<re.Match object; span=(, ), match='hello 123 4567 World_This is a regex Demo'>
hello World_This is a regex Demo
(, )
[Finished in .1s]

正则表达式

常用的匹配模式:
\w 匹配字母数字及下划线
\W 匹配f非字母数字下划线
\s 匹配任意空白字符,等价于[\t\n\r\f]
\S 匹配任意非空字符
\d 匹配任意数字
\D 匹配任意非数字
\A 匹配字符串开始
\Z 匹配字符串结束,如果存在换行,只匹配换行前的结束字符串
\z 匹配字符串结束
\G 匹配最后匹配完成的位置
\n 匹配一个换行符
\t 匹配一个制表符
^ 匹配字符串的开头
$ 匹配字符串的末尾
. 匹配任意字符,除了换行符,re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符
[....] 用来表示一组字符,单独列出:[amk]匹配a,m或k
[^...] 不在[]中的字符:[^abc]匹配除了a,b,c之外的字符
* 匹配0个或多个的表达式
+ 匹配1个或者多个的表达式
? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
{n} 精确匹配n前面的表示
{m,m} 匹配n到m次由前面的正则表达式定义片段,贪婪模式
a|b 匹配a或者b
() 匹配括号内的表达式,也表示一个组
[\u4e00-\u9fa5] :匹配中文
(\d{}-\d{}-\d{}) : 匹配日期
.*? :匹配任意字符串
\[(\d{}-\d{}-\d{})\] 匹配时间 eg:[--] for content in contents:
try:
# 替换文本
s = str(content).replace('y,','')#.replace('<', '-5')
s = s.replace('年', '-').replace('月', '-').replace('日', '')
s = s.replace('(', '').replace(')', '').replace('\'', '')
content = s.split(',') # s = str(content).replace('/','-') #
# s = re.sub('(\d{4}-\d{2})',r'\1-',s)
# s = s.replace('(', '').replace(')', '').replace('\'', '')
# content = s.split(',') list.append(content) except EOFError as e:
print(e)
continue
return list

正则表达式匹配练习

1、匹配猫眼电影top100的电影名、主演、上映日期

对应正则表达式:'class="name".*?title="(.*?)".*?:(.*?)\s*?</p>.*?:(\d{4}-\d{2}-\d{2})'

2、匹配猫眼电影top100的海报图片

对应的正则表达式:'img\sdata-src="(.*?)"\salt'

3、匹配西南大学计算机学院讲座信息

 '<li><span\sclass="fr">\[(\d{4}-\d{2}-\d{2})\].*?&nbsp;&nbsp;(.*?)</a></li>',

python 网页爬虫 基础篇的更多相关文章

  1. Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)

    原文:http://www.52nlp.cn/python-网页爬虫-文本处理-科学计算-机器学习-数据挖掘 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开 ...

  2. 【Python】Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱

    本文转载自:https://www.cnblogs.com/colipso/p/4284510.html 好文 mark http://www.52nlp.cn/python-%E7%BD%91%E9 ...

  3. 深度学习入门者的Python快速教程 - 基础篇

      5.1 Python简介 本章将介绍Python的最基本语法,以及一些和深度学习还有计算机视觉最相关的基本使用. 5.1.1 Python简史 Python是一门解释型的高级编程语言,特点是简单明 ...

  4. [资料分享]Python视频教程(基础篇、进阶篇、项目篇)

    Python是一种开放源代码的脚本编程语言,这种脚本语言特别强调开发速度和代码的清晰程度.它可以用来开发各种程序,从简单的脚本任务到复杂的.面向对象的应用程序都有大显身手的地方.Python还被当作一 ...

  5. Python学习笔记基础篇——总览

    Python初识与简介[开篇] Python学习笔记——基础篇[第一周]——变量与赋值.用户交互.条件判断.循环控制.数据类型.文本操作 Python学习笔记——基础篇[第二周]——解释器.字符串.列 ...

  6. python从爬虫基础到爬取网络小说实例

    一.爬虫基础 1.1 requests类 1.1.1 request的7个方法 requests.request() 实例化一个对象,拥有以下方法 requests.get(url, *args) r ...

  7. Python扫描器-爬虫基础

    0x1.基础框架原理 1.1.爬虫基础 爬虫程序主要原理就是模拟浏览器发送请求->下载网页代码->只提取有用的数据->存放于数据库或文件中 1.1.基础原理 1.发起HTTP请求 2 ...

  8. Python BeautifulSoup4 爬虫基础、多线程学习

    针对 崔庆才老师 的 https://ssr1.scrape.center 的爬虫基础练习.Threading多线程库.Time库.json库.BeautifulSoup4 爬虫库.py基本语法

  9. Python网页爬虫(一)

    很多时候我们想要获得网站的数据,但是网站并没有提供相应的API调用,这时候应该怎么办呢?还有的时候我们需要模拟人的一些行为,例如点击网页上的按钮等,又有什么好的解决方法吗?这些正是python和网页爬 ...

随机推荐

  1. python-python基础7

    一.静态方法 通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类 ...

  2. jqGrid 多选复选框 编辑列 方法事件

    参考:https://blog.csdn.net/zsq520520/article/details/53375284?locationNum=8&fps=1

  3. Linux --xrandr command

    Source: https://www.x.org/archive/current/doc/man/man1/xrandr.1.xhtml https://blog.csdn.net/syh_486_ ...

  4. 三、js提交请求加载启动动画、请求完成成功回调、注销加载动画

    1.通过Query  post方式进行异步请求方法 jQuery.post(url, [data], [callback], [type]) 参数说明: url:发送请求地址 data:待发送 Key ...

  5. String类与StringBuffer类

    String类与StringBuffer类   一.String类和StringBuffer类的区别 String类是不可变类,新建的对象为不可变对象(String类的内容和长度是固定的),一旦被创建 ...

  6. 谈一下你对uWSGI和 nginx的理解(原理)

    要注意 WSGI / uwsgi / uWSGI 这三个概念的区分. WSGI是一种通信协议. uwsgi是一种线路协议而不是通信协议,在此常用于在uWSGI服务器与其他网络服务器的数据通信. uWS ...

  7. 【高软作业3】:原型化系统 DevTools

    原型化系统:DevTools       密码:lcx 1. 这是一个什么样的平台? DevTools,可译为:开发者工具库.初衷是聚集各类开发工具,方便开发者获取:此外,大家可以分享自己的工具库与工 ...

  8. 01.DesignParttern设计模式,简单工厂,工厂方法,抽象工厂三大工厂的区别与联系

                工厂用来生产对象,对象具有方法和属性. 简单工厂的缺点(简单工厂并不是23中设计模式): 工厂类的职责相对过重,增加新的产品,需要修改工厂类的判断逻辑,违背开闭原则: JDK源 ...

  9. CodeForces - 862C Mahmoud and Ehab and the xor(构造)

    题意:要求构造一个n个数的序列,要求n个数互不相同,且异或结果为x. 分析: 1.因为0 ^ 1 ^ 2 ^ 3 ^ ... ^ (n - 3) ^ (n - 2) ^ (0 ^ 1 ^ 2 ^ 3 ...

  10. DB2常用sql语句

    转 DB2 提供了关连式资料库的查询语言sql(structured query language),是一种非常口语化.既易学又易懂的语法.此一语言几乎是每个资料库系统都必须提供的,用以表示关连式的操 ...