一个简易的Python爬虫,将爬取到的数据写入txt文档中

代码如下:

import requests
import re
import os

#url
url = "http://wiki.akbfun48.com/index.php?title=%E4%B9%83%E6%9C%A8%E5%9D%82%E5%B7%A5%E4%BA%8B%E4%B8%AD&variant=zh-hans"

#请求头
headers = {

    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
    "Referer":url
}

r = requests.get(url,headers=headers)
if r.status_code == 200:        #响应200为请求成功
    r.encoding = r.apparent_encoding        #转换字符编码
    html = r.text

    #正则表达式匹配数据,获取数据列表
    list = re.findall(r'>http://www.bilibili.com/video/av.*\/<',html)
    count = 0
    #循环列表,将数据写入txt文档中
    for i in list:
        count += 1
        #如果没有txt文件则新建文件,并执行写入操作
        with open("abc.txt",'a',encoding='utf-8') as f:
            f.write("ep"+str(count)+i+'\n')
            print("success")
else:
    print(404)

运行效果如下:

执行后,会在本程序的路径下新建abc.txt文件,并保存爬取的数据

猜你喜欢

转载自www.cnblogs.com/Hotaru-Xin/p/10713428.html