正则表达式
字符 | 含义 |
---|---|
abc | 一个abc |
[…] | 匹配[]中出现的任意一个字符 |
[0-9] | 表示匹配0-9任意一个数字 |
(abc|李四|小红) | 表示匹配abc或李四或小红 |
(abc|李四|小红){2,3} | 表示匹配abc或李四或小红2次或3次 |
^abc | 表示要匹配的字符串必须要以a开头 |
abc$ | 表示要匹配的字符串必须要以c结尾 |
元字符
符号 | 含义 |
---|---|
. | 任意一个字符 |
\d | 一个数字 |
\s | 一个空格 |
\b | 单词边界(单词的左边或右边有空格的) |
\w | 一个字母.数字.下划线甚至一个中文 |
或\D | 一个数字之外的字符/ 大写取和小写相反的 |
量词
符号 | 含义 |
---|---|
a{3} | 表示aaa |
d{2,4} | 表示dd或ddd或dddd |
{n,m} | 表示一个字符要匹配n-m次 |
+ | 表示{1,},一次或多次 |
* | 表示{0,},任意次,0次或多次 |
? | 表示{0,1},0次或1次 |
re模块
import re # 导入模块
str = "a123b456b789b"
reg = re.compile('[a-zA-z]\d') # 创建正则规则
# print(re.search(reg, str)) # 查找字符存不存在,不存在会返回None
result = re.findall(reg, str) # 把结果找出来,并返回一个列表
print(result)
# 贪婪模式
reg2 = re.compile('a.+b')
print(re.findall(reg2, str)) # 这会匹配到全部的字符串
# 非贪婪模式
reg3 = re.compile('a.+?b')
print(re.findall(reg3,str3)) # 这只会匹配到"a123b"
re模块的贪婪模式会尽可能匹配多的字符串
requests模块
import requests # 1-导入模块
import chardet # 用于获取页面源码的编码形式
url = "http://www.baidu.com" # 2-准备网址
user_agent = [
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"] # 游览器头部信息
res = requests.get(url, headers={"User-Agent":random.choice(user_agent)}) # 3-访问网址和添加访问游览器时的头部信息
encode = chardet.detect(res.content) # 获取页面的编码形式,返回的是一个字典
res.encoding = encode.get('encoding') # 设置编码
print(res.text) # 4-显示页面纯文本信息
get()方法的常用参数:
url: 这是要发送请求的网页链接
headers: 这是访问网页时的游览器头部信息,必须是一个字典,这是可选的
proxies: 这个参数可以设置代理IP ,必须是一个字典,这是可选的
BeautifulSoup模块
from bs4 import BeautifulSoup # 导入模块
html = """
<html>
<head> <title>The Dormouse's story</title> </head>
<body>
<h1><b>123456</b></h1>
<p class="title" name="dromouse">
<b>The Dormouse's story</b>
aaaaa
</p>
<p class="title" name="dromouse" title='new'><b>The Dormouse's story</b>a</p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
<a href="http://example.com/tillie" class="siterr" id="link4">Tillie</a>;
<a href="http://example.com/tillie" class="siterr" id="link5">Tillie</a>;
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
<ul id="ulone">
<li>01</li>
<li>02</li>
<li>03</li>
<li>04</li>
<li>05</li>
</ul>
<div class='div11'>
<ul id="ultwo">
<li> 0001 </li>
<li>0002</li>
<li>0003</li>
<li>0004</li>
<li>0005</li>
</ul>
</div>
</body>
</html>
"""
# 转为bs4对象
soup = BeautifulSoup(html,'html.parser')
# XXX找第一个yy标签
# print(soup.title)
# print(soup.find("title"))
#
# # 标签的文本内容
# print(soup.find("title").text)
#
# # 根据id找对象
# ul = soup.find(id="ulone")
# print(ul)
#
# # 根据class找对象,参数
# print(soup.find(class_='title'))
# # 细化查找
# print(soup.find('p', class_='title'))
#
# # 通用写法,字典中可以有多个条件
# print(soup.find('p',attrs={"name":"名字"}))
a = soup.find(class_='story').find('a')
# 显示a对象的所有属性和属性值,这是一个字典
print(a.attrs)
find()方法会找到第一个和它匹配的标签,且只会找一个
如果想找多个,请用find_all()方法,它是查找所有的匹配项,并返回一个列表
抓取 彼岸壁纸 图片链接
使用 requests+bs4 抓取 彼岸壁纸 图片链接,并存储到csv文件
import requests # 1-准备工具
import chardet
import random
from bs4 import BeautifulSoup
import csv
def get_html(url):
user_agent = [
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"
] # 游览器头部信息
res = requests.get(url, headers={"User-Agent": random.choice(user_agent)}) # 3-访问网址和添加访问游览器时的头部信息
encode = chardet.detect(res.content) # 获取网页的编码形式
res.encoding = encode.get('encoding') # 设置编码
return res
if __name__ == "__main__":
url ="http://www.netbian.com/"
html = get_html(url).text
soup = BeautifulSoup(html,"html.parser")
img_list = soup.find('div', class_='list').find_all('img')
list = []
for i in img_list:
list.append([i.attrs['src']])
# 将链接写入CSV
with open("壁纸链接.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows(list)