读文件
open(文件路径,'r',encoding='utf-8)#'r'是读模式,encoding是编码方式
print(f.read())#会读取全部的文件内容,并打印
print(f.read()#会读空字符串,会接着上次读取的地方继续读取,并打印
注意:read不适用读取大文件,可以在read(字节长度)
f.close()#关闭文件
下面的写法不用单独的调用close
with open("./data.txt") as f:
print(f.read())#对文件的操作
f=open('./data.txt','r',encoding='utf-8')
content=f.read()
print(content)
f.close()
with open('./data.txt','r',encoding='utf-8') as f:
c=f.read()
print(c)
f.readline()#逐行读取
with open('./data.txt','r',encoding='utf-8') as f:
print(f.readline())#逐行读取
print(f.readline())
写入文件:with open('./data.txt','w','r') as f:
注1:w模式下,用w会清空源文件的内容
with open('./data.txt','w',encoding='utf-8') as f:
f.write('say hello a\n')
a表示附加模式,即在源文件的后面追加
a也是只写不读
with open('./data.txt','a',encoding='utf-8') as f:
f.write('say hello a\n')
r+是读写模式
with open('./data.txt','r+',encoding='utf-8') as f:
f.write('say hello a\n')
c=f.read()
print(c)
捕捉异常
try:
异常的代码
except ValueError:
print("输入不合理的数字,请重新运行程序,并输入正确的数字")
except ZeroDivisionError:
print("修改")#产生零错误时会运行
except:
print("捕捉所有错误")#产生其他错误时会运行
else:
print('正确执行的案例'+str(user_data))#没有错误时会运行
feinally:
print('最终都会执行')
assert断言
assert +测试代码
unittest常见的单元测试库,单元测试库是对软件中最小的可测试单元进行验证,比如验证某函数某方面是否符合预期,这个库是自带的
网站的robots.txt了解网站的可爬范围
用requests发送请求
import requests as re
head={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}#把爬虫程序伪装成正常浏览器
response=re.get('https://movie.douban.com/top250',headers=head)#注意是headers,后面有s
if response.ok:
print(response.text)
else:
print('请求失败')
状态码:
418 i am a teapot服务器不想理你这个请求,可以通过定义请求头,把程序伪装成浏览器
200代表请求成功
HTML网页结构
HTML :网页结构和信息
CSS:定义网页的样式
JavaScript:定义用户和网页的交互逻辑
每一个<>里面都是一个html标签
<!DOCTYPE HTML>用来告知浏览器这个文件类型是HTML
<meta http-equiv="Content-Type"content="tect/html;charset=utf-8"/>防止中文乱码
<html>起始标签,表示开始
<body>
<h1>这是一个标题,一级标题,最大的标题</h1>
<p>这是一段文字</p>
</body>
</html>结束标签,表示结束
![](https://img-blog.csdnimg.cn/img_convert/e38e2f97a5ee2d3d3447a64389876932.png)
<br>标签可以强制换行,且只有起始标签没有配对的闭合标签。
<b><b/>对文字内容进行加粗
<i><i/>文字变为斜体
<u></u>加下划线
<img src="https://images...." width="500px" height="">加图片没有闭合标签src需要我们指定一个属性,表示图片的路径,他的值可以是指向图片的一个链接,也可以是路径,src属性必须指定值。
<a href="" target="_self">我的主页<>用来添加链接,用户可以通过链接在不同的网页之间跳来跳去,在起始和闭合的链接之间,放上连接对应的文字,展示给用户不再是原始直白的地址。target可写可不写,用来指定链接的打开方式。 默认是"_self",表示直接在当前窗口跳转链接。"_blank"表示在新窗口里打开。
![](https://img-blog.csdnimg.cn/img_convert/25746d7514272bea6b317a752b0945b1.png)
<div><span>都是容器,例如给容器里所有元素加上红色背景,可以将css直接渲染在容器上。
方式一
div是块级元素,独占自己的一块,一行最多放一个div元素
<div style="background-color:red">
<p>你好</p>
</div>
方式二
span是内联元素,不会独占一块,一行可以有多个span元素
<span style="background-color:red">
<p>你好</p>
</span>
<ol>表示列表,定义的是有序列表
<ol>
<li></li>
<li></li>
</ol>
<ul>定义的是无序列表
<ul>
<li></li>
</ul>
<table></table>里面会嵌套一些和表格相关的元素
<table border="1">border=1表示的是默认表格没有边框,
<thead>表示表格的头部
<tr>定义表格行
<td>表头1<td/>
<td>表头2<td/>
</tr>
</thead>
<tbody>表示表格的主体
<tr>定义表格行
</tr>
</tbody>
</table>
![](https://img-blog.csdnimg.cn/img_convert/3073b5a99877ec937c82d415a580f83c.png)
class可以运用在所有的标签上,定义元素的类的名称,类用来分组。
<p class="content">给岁月以文明</p>
<p class="content">而不是给文明以岁月</p>
<p class="review">五星好评!</p>
![](https://img-blog.csdnimg.cn/img_convert/32636f81fa452e6a88fe641e1572948a.png)
BeautifulSoup解析HTML内容
先引用库
from bs4 import BeautifulSoup
import requests
cntent=requests.get('链接').text
soup=beautifulsoup(content,"html.parser")
beautifulsoup会把文件解析为类似树状的结构,简化搜索和修改HTML的过程
soup.p是<p></p>中的文本段落元素
all_prices=soup.findAll("p",attrs={"class":"price_color"}))
soup.findAll("p")根据标签属性等找出所有符合要求的元素,假如第一个元素为p,表示找p标签,传入可选参数attrs={},键值对,对应想找的属性和值,例如attrs={"class": "price_color"})我们想要找的是class属性的值为price_color的元素。findAll会返回一个可迭代的对象,我们可以通过for循环,依次操作返回的各个对象。
打印对象如下
for price in all_price:
print(price.string[2:])#打印标签包围的字符串,切片限定范围
豆瓣top250电影名字爬虫
import requests as re
from bs4 import BeautifulSoup
head={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'}#把爬虫程序伪装成正常浏览器
for start_num in range(0,250,25):#实现分页
response=re.get(f'https://movie.douban.com/top250?start={start_num}&filter=',headers=head)#注意是headers,后面有s
html=response.text
soup1=BeautifulSoup(html,"html.parser")#后面是html解析器
all_title=soup1.findAll('span',attrs={"class":"title"})
for titles in all_title:
title=titles.string
if '/' not in title:
print(title)