入门Python爬虫Day3

python爬虫

此文章大致需要观看八分钟


Python作为现阶段最流行的语言,对于网络的爬取和海量数据的分析,python更胜一筹。

  • 今天介绍一下re库以及BeautifulSoup库。
    • re库采用raw string类型表示正则表达式,通常被用来检索、替换那些符合某个模式(规则)的文本。
    • BeautifulSoup是爬虫必学的技能。BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,主要的功能是如何解析和提取 HTML/XML 数据。
安装BeautifulSoup第三方库
  • 此次安装需要使用命令行安装requests库。
pip install beautifulsoup4

此方法可直接在site-package中安装bs4库,如果遇到Permission问题出现,则需要使用管理员运行命令行。

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

若没出现报错现象,则说明安装成功。


在这里我们先分享一下BeautifulSoup的官方文档:
http://beautifulsoup.readthedocs.org/zh_CN/latest


字符串截取

Python字符串截取的规则为“前闭后开”,Python索引有两种方式,从左往右为从0开始逐一递增,从右往左为从-1开始逐一递减。

# 字符串截取
str = 'ABCDEFG'
# 截取第一位到第三位的字符
print('截取第一位到第三位的字符: ' + str[0:3:])
# 截取字符串的全部字符
print('截取字符串的全部字符: ' + str[::])
# 截取第七个字符到结尾
print('截取第七个字符到结尾: ' + str[6::])
# 截取从头开始到倒数第三个字符之前
print('截取从头开始到倒数第三个字符之前: ' + str[:-3:])
# 截取第三个字符
print('截取第三个字符: ' + str[2])
# 截取倒数第一个字符
print('截取倒数第一个字符: ' + str[-1])
# 与原字符串顺序相反的字符串
print('与原字符串顺序相反的字符串: ' + str[::-1])
# 截取倒数第三位与倒数第一位之前的字符
print('截取倒数第三位与倒数第一位之前的字符: ' + str[-3:-1:])
# 截取倒数第三位到结尾
print('截取倒数第三位到结尾: ' + str[-3::])
# 逆序截取
print('逆序截取: ' + str[:-5:-3])


字符串转换与变换

python内置函数replace:Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法为:str.replace(old, new[, max])

str = 'ABCABCABC'
# 单个内容替换
print(str.replace('C', 'V'))
# 输出内容:ABVABVABV

# 字符串替换
print(str.replace('BC', 'WV'))
# 输出内容:AWVAWVAWV
# 替换成特殊符号(空格)
print(str.replace('BC', ' '))
# 输出内容:A A A

字符串find寻找

python内置函数find:Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
语法:str.find(str, beg=0, end=len(string))

str = 'ABCDABC'
# 查找全部
print(str.find('A'))
# 输出内容:0

# 从字符串第四个开始查找
print(str.find('A', 3))
# 输出内容:4

# 从字符串第二个到第六个开发查找
print(str.find('C', 1, 5))
# 输出内容:2

# 查找不存在的内容
print(str.find('E'))
# 输出内容:-1

字符串index寻找

python内置函数index:Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
语法:str.index(str, beg=0, end=len(string))

str = 'ABCDABC'
# 查找全部
print(str.index('A'))
# 输出内容:0

# 从字符串第四个开始查找
print(str.index('A', 3))
# 输出内容:4

# 从字符串第二个到第六个开发查找
print(str.index('C', 1, 5))
# 输出内容:2

# 查找不存在的内容
print(str.index('E'))
# 输出内容:ValueError: substring not found

字符串分割

python内置函数split:Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串。
语法:str.split(str="", num=string.count(str))

str = 'ABCDABC'
# 分割全部
print(str.split('B'))
# 输出内容:['A', 'CDA', 'C']
# 分割一次
print(str.split('B', 1))
# 输出内容:['A', 'CDABC']

构造12306字典

首先我们了解到12306的station_name分布在一个js文件中,我们可以使用python访问这个网页进行查看,发现数据是使用“|”字符串分割,位次以及名称使用"@"字符串分割。
放上12306字典链接:
https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9031

import requests
def city_name():
    # 构建请求头
    headers = {'User-Agent':
               'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
               '(KHTML, like Gecko) Chrome/63.0.3218.0 Safari/537.36',
               'Referer':
               'https://kyfw.12306.cn/otn/login/init'}
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9031'
    city_code = requests.get(url, headers=headers, verify=False)
    # 数据使用字符串操作处理
    city_code_list = city_code.text.split("|")
    city_dict = {}
    for k, i in enumerate(city_code_list):
        if '@' in i:
			# 城市名作为字典的键,城市编号作为字典的值
            city_dict[city_code_list[k + 1]] = city_code_list[k + 2].replace(' ', '')
    return (city_dict)
# 输出处理后的数据
print(city_name())

re.match的应用

python内置库re中re.match:re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
语法:re.match(pattern, string, flags=0)

  • 首先先引入内置库re,定义一个想要寻找的字符串:
import re
text = "This is the last one"
  • 使用re.match开始寻找想要的字符串:
res = re.match('(.*) is (.*?) .*', text, re.M | re.I)
  • 判断字符串是否存在,若存在则匹配对象函数来获取匹配表达式。(ps:使用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 last 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!!")

re.findall的应用(重点)

python内置库re中re.findall:在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
语法:re.findall(string[, pos[, endpos]])

  • 首先先日常引入re库:
import re
  • 匹配字符串中所有含有’oo’字符的单词,当正则表达式中没有圆括号时,列表中的字符串表示整个正则表达式匹配的内容:
find_value = re.findall('\w*oo\w*', 'woo this foo is too')
print(find_value)
  • 获取字符串中所有的数字字符串,当正则表达式中只带有一个圆括号时,列表中的元素为字符串,并且该字符串的内容与括号中的正则表达式相对应。
find_value = re.findall('.*?(\d+).*?', 'adsd12343.jl34d5645fd789')
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)

上述完整代码为:

import re

find_value = re.findall('\w*oo\w*', 'woo this foo is too')
print(find_value)

find_value = re.findall('.*?(\d+).*?', 'adsd12343.jl34d5645fd789')
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)

  • 首先导入re模块:
import re
  • 将手机号的后4位替换成0:
replace_value = re.sub('\d{4}$', '0000', '13435423143')
print(replace_value)
  • 将代码后面的注释信息去掉:
replace_value = re.sub('#.*$', '', 'num = 0 #a number')
print(replace_value)

上述完整代码为:

import re

replace_value = re.sub('\d{4}$', '0000', '13435423143')
print(replace_value)

replace_value = re.sub('#.*$', '', 'num = 0 #a number')
print(replace_value)

BeautifulSoup的应用

介绍之前,我们了解BeautifulSoup是用来解析和提取 HTML/XML 数据使用的。
在这里我们先创建一个HTML文档,并命名为MySoup.html。

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title> Python</title> 
</head>
<body>
<p id="python">
<a href="/index.html"> Python </a>BeautifulSoup的使用
</p>
<p class=”myclass”>
<a href="http://www.baidu.com/">这是</a> 一个指向百度的页面的URL。
</p>
</body>
</html>

我们首先要导入BeautifulSoup第三方库

from bs4 import BeautifulSoup

分析HTML则需要在python中打开HTML文件,并将HTML文件里的内容赋值给一个变量,并关闭文件。

Open_file = open('MySoup.html', 'r', encoding='utf-8')
Html_Content = Open_file.read()
Open_file.close()

在这里我们使用常用的html5lib解释器解释HTML中的内容,并将它输出。

soup = BeautifulSoup(Html_Content, "html5lib")
print('html title is ' + soup.title.getText())

对HTML解析之后方可获取HTML中想获取的内容。在这里演示一下获取单个p标签和全部p标签的方法

find_p = soup.find('p', id="python")
print('the first <p> is ' + find_p.getText())
##########
find_all_p = soup.find_all('p')
for i, k in enumerate(find_all_p):
    print('the ' + str(i + 1) + ' p is ' + k.getText())

上述完整为:

# 引入BeautifulSoup
from bs4 import BeautifulSoup
# 读取MySoup.html文件
Open_file = open('MySoup.html', 'r', encoding='utf-8')
# 将MySoup.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())

BeautifulSoup的实例

首先在代码中定义Html_content字符串,作为解析内容:

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>"""

导入BeautifulSoup模块并使用html5lib进行解析,赋变量为soup:

from bs4 import BeautifulSoup
soup = BeautifulSoup(Html_content, "html5lib")

获取头部的信息,返回之间的全部内容:

print(soup.head)

获取title的信息,返回之间的全部内容:

print(soup.title)

在这里有一个获取tag的小窍门,可以在文档树的tag中多次调用这个方法.下面的代码可以获取标签中的第一个标签,也就是说,soup不一定是整个html的内容,可以先定位某部分,然后用这简洁方式获取:

print(soup.body.b)
# 输出"<b>Beautiful Soup的学习</b>"

直接指定标签类别,返回第一个标签的内容:

print(soup.a)
# 输出"<a href="www.xxx.com" class="abc" id = "try1">web开发</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>]

上述完整代码为:

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>]

发布了13 篇原创文章 · 获赞 25 · 访问量 1494

猜你喜欢

转载自blog.csdn.net/qq_45414559/article/details/105189782