Python爬虫re库和beautifulsoup库的应用

python爬虫篇

这篇教程主要包括re库以及BeautifulSoup库。
  • re库采用raw string类型表示正则表达式,通常被用来检索、替换那些符合某个模式(规则)的文本。

  • BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,主要的功能是解析和提取HTML/XML 数据。


re.match的应用

语法:re.match(pattern, string, flags=0)

  • 首先引入内置库re,定义需要寻找的字符串:
import re
text = "This is the first one"
  • 使用re.match开始寻找想要的字符串:
res = re.match('(.*) is (.*?) .*', text, re.M | re.I)
  • 判断字符串是否存在,若存在则使用group(num) 或 groups()匹配对象函数来获取匹配表达式。
if res:
    print("res.group() : ", res.group())
    print("res.group(1) : ", res.group(1))
    print("res.group(2) : ", res.group(2))
    print("res.groups() : ", res.groups())
else:
    print("No match!!")

源码如下:

import re
text = "This is the first one"
res = re.match('(.*) is (.*?) .*', text, re.M | re.I)
if res:
    print("res.group() : ", res.group())
    print("res.group(1) : ", res.group(1))
    print("res.group(2) : ", res.group(2))
    print("res.groups() : ", res.groups())
else:
    print("No match!!")

输出结果:
res.group() :  This is the first one
res.group(1) :  This
res.group(2) :  the
res.groups() :  ('This', 'the')
  • 匹配字符串中所有含有’oo’字符的单词,当正则表达式中没有圆括号时,列表中的字符串表示整个正则表达式匹配的内容:
find_value = re.findall('\w*oo\w*', 'poo this foo is roo')
print(find_value)

输出结果:
['poo', 'foo', 'roo']
  • 获取字符串中所有的数字字符串,当正则表达式中只带有一个圆括号时,列表中的元素为字符串,并且该字符串的内容与括号中的正则表达式相对应。
find_value = re.findall('.*?(\d+).*?', 'bqfh62543.glh67d369wfb3895')
print(find_value)

输出结果:
['62543', '67', '369', '3895']
  • 提取字符串中所有的有效的域名地址,正则表达式中有多个圆括号时,返回匹配成功的列表中的每一个元素都是由一次匹配成功后,正则表达式中所有括号中匹配的内容组成的元组。
add = 'https://www.net.com.edu//action=?asdfsd and other https://www.baidu.com//a=b'
find_value = re.findall('((w{3}\.)(\w+\.)+(com|edu|cn|net))', add)
print(find_value)

输出结果:
[('www.net.com.edu', 'www.', 'com.', 'edu'), ('www.baidu.com', 'www.', 'baidu.', 'com')]

源代码:

import re
find_value = re.findall('\w*oo\w*', 'poo this foo is roo')
print(find_value)

find_value = re.findall('.*?(\d+).*?', 'bqfh62543.glh67d369wfb3895')
print(find_value)

add = 'https://www.net.com.edu//action=?asdfsd and other https://www.baidu.com//a=b'
find_value = re.findall('((w{3}\.)(\w+\.)+(com|edu|cn|net))', add)
print(find_value)

re.sub的应用

python内置库re中re.sub:用于替换字符串中的匹配项。
语法:re.sub(pattern, repl, string, count=0, flags=0)

  • 将手机号的后6位替换成0:
import re
replace_value = re.sub('\d{6}$', '000012', '13888888888')
print(replace_value)

输出结果:
13888000012

BeautifulSoup

BeautifulSoup是用来解析和提取 HTML/XML 数据使用的

安装BeautifulSoup第三方库

pip install beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple

使用python3对已下载的第三方包bs4进行调试。

 from bs4 import BeautifulSoup

创建一个html文档

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Python</title>
</head>
<body>
<p id="python">
<a href="/index.html"> Python BeautifulSoup</a>
</p>
<p class=”myclass”>
<a href="http://www.baidu.com/">百度页面</a>
</p>
</body>
</html>

BeautifulSoup示例源码:

# 引入BeautifulSoup
from bs4 import BeautifulSoup
# 读取soup.html文件
Open_file = open('MySoup.html', 'r', encoding='utf-8')
# 将soup.html的内容赋值给Html_Content,并关闭文件
Html_Content = Open_file.read()
Open_file.close()
# 使用html5lib解释器解释Html_Content的内容
soup = BeautifulSoup(Html_Content, "html5lib")
# 输出title
print('html title is ' + soup.title.getText())
# 查找第一个标签p,并输出
find_p = soup.find('p', id="python")
print('the first <p> is ' + find_p.getText())
# 查找全部标签p,并输出
find_all_p = soup.find_all('p')
for i, k in enumerate(find_all_p):
    print('the ' + str(i + 1) + ' p is ' + k.getText())

输出结果:
html title is  Python
the first <p> is 
 Python BeautifulSoup
the 1 p is 
 Python BeautifulSoup
the 2 p is 
百度页面
Html_content = """<html><head><title> Python</title></head>
<p class="title"><b>Beautiful Soup的学习</b></p>
<p class="study">学习网址:http://blog.csdn.net/huangzhang_123
 <a href="www.xxx.com" class="abc" id="try1">web开发</a>,
<a href=" www.ccc.com " class="bcd" id="try2">网络爬虫</a> and
<a href=" www.aaa.com " class="efg" id="try3">人工智能</a>;
</p>
<p class="other">...</p>"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(Html_content, "html5lib")
# 以下是查找某标签的方法:
# 获取头部的信息,返回<head></head>之间的全部内容
print(soup.head)
# 获取title的信息,返回<title></title>之间的全部内容
print(soup.title)
# 这是个获取tag的小窍门,可以在文档树的tag中多次调用这个方法.下面的代码可以获取<body>标签中的第一个<b>标签,
# 也就是说,soup不一定是整个html的内容,可以先定位某部分,然后用这简洁方式获取,返回
# "<b>Beautiful Soup的学习</b>"
print(soup.body.b)
# 直接指定标签类别,返回第一个标签的内容。返回 "<a href="www.xxx.com" class="abc"
# id = "try1">web开发</a>"
print(soup.a)
# 获取全部的标签a。
print(soup.find_all('a'))
#[<a href="www.xxx.com" class="abc" id="try1">web开发</a>,
#<a href=" www.ccc.com " class="bcd" id="try2">网络爬虫</a>,
#<a href=" www.aaa.com " class="efg" id="try3">人工智能</a>]


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值