简单的请求网页写入txt文档
import requests
import re
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36"
}
url = "https://labfile.oss.aliyuncs.com/courses/3086/lanqiao.html"
res = requests.get(url=url, headers=headers)
res.encoding = 'utf-8'
html_data = res.text
# 匹配数据,获取所有的课程标题
results = re.findall('<h6 title="(.*)" class="course-name"', html_data)
for item in results:
# 格式化字符串
new_str = "课程名:{item}\n".format(item=item)
# 将格式化之后的数据写入文件
# './data.txt' 存储的文件名,其中 ./ 表示当前目录。
# a 打开文件的模式:只读 r,写入 w,追加 a 等,具体可以参考:学习地址。
# encoding="utf-8" 文件编码。
with open("./data.txt", "a", encoding="utf-8") as f:
f.write(new_str)