# day5

- Link: https://xingheye.icu/day5/
- Published: 2026-11-01T22:59:27+08:00
- Author: 星和夜

```
    from email import header

    import requests
    import os
    import re
    import csv

    def fetch_page(url,cookie=None):
        if not cookie:
            res=requests.get(
                url=url,
                headers={
                    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.3'
                }
            )
        else:
            res = requests.get(
                url=url,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.3',
                    'cookie':cookie
                }
            )

        html_code = res.text
        return html_code

    def parse_page(html_code):
        title_pattern = re.compile(r'<span class="title">([^<]+)</span>[\s\S]*?<span class="rating_num"[^>]*>([\d.]+)</span>[\s\S]*?<span>(\d+)人评价</span>')     # 具体正则表达式可以让AI写
        titles = title_pattern.findall(html_code)
        return titles

    def save_to_csv(titles,file_name,header):           # csv是逗号分隔值文件，打开之后像是execl表格，但是没有大小限制
        with open(file_name,'w',encoding='utf-8') as f:
            writer=csv.writer(f)
            writer.writerow(header)
            writer.writerows(titles)


    def main():
        html_code=fetch_page('https://movie.douban.com/top250')
        titles=parse_page(html_code)
        save_to_csv(titles,'douban.csv',['电影名','评分','评论人数'])
    if __name__ == '__main__':
        main()
    ```

    ```
    def parse_page(html_code): title_pattern = re.compile(r'<title>(.+?)</title>') # 具体正则表达式可以让AI写 titles = title_pattern.findall(html_code) return titles def main(): html_code=fetch_page('https://bilibili.com/') return parse_page(html_code) if __name__ == '__main__': print(main())
    ```

#open()创建一个文件，默认只读方式打开，括号填文件名，返回文件对象
 #read(n)从文件
中读取n长度的数据，默认为无穷 #readline()一次性读一行 #read

#write()写入内容
 #close()关闭 #closed()检查文件是否关闭，反回布尔值 #.name返回文件
名 #.mode返回文件打开方式，r为只读

# f=open(‘列表.py’,encoding=’utf-8′)
 with open(r”C:\Users\19880\Desktop\新建文件
夹\致橡树.txt”,’r’,encoding=’utf-8′) as f: print(f.read())

”’文本文件访问模式，访问图片视频要二进制，使用+会影响效率
 r只读，文件不存在则报
错 r+可读可写，报错 w只写，文件不存在则创建(先清空原有内容再写) w+可读可写，创建(
先清空原有内容再写) a只读，创建(原有基础添加内容) a+可读可写，创建(原有基础添加内容)”’

#文件指针
 # tell()显示文件指针当前位置 # seek(offset,whence)移动光标到指定位置 #
offset偏移量，表示要移动的字节数 #whence起始位置，表示移动字节数的参考位置，默认
为0，表示文件开头，1表示当前位置，2表示文件末尾

#with open操作结束后自动调用close方法

import os
 #1.文件重命名os(‘旧名字’，’新名字‘) #2.删除文件os.remove(‘要删除的文件’)#
3.创建文件夹（注意是文件夹不是文件）os.mkdir(‘文件夹名’) #4.删除文件夹os.rmdir()#
5.获取当前目录 print(os.getcwd()) #6.提取目录列表 print(os.listdir()) print(os.listdir(‘../’))
