爬取星座

#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import requests
from bs4 import BeautifulSoup
import csv
import os
import re
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
}
link = "https://www.xzw.com/fortune/"
fetch_regex = re.compile(r"^.*?<strong>(.*?)</strong><small>(.*?)</small>.*?width:(\d*)%.*?<p>(.*?)\[<a.*$",re.S)
save_path = os.path.join(os.getcwd(),"data.csv")

def fetch_msg(url):
    resp = requests.get(url,headers=headers)
    resp.encoding = "utf-8"
    resp = resp.text
    soup = BeautifulSoup(resp,"lxml")

    dls = soup.select("#list > div.alb dl")
    result_list = []
    for dl in dls:
        result = fetch_regex.match(str(dl))
        if result:
            result_list.append([result.group(1),result.group(2),str(int(result.group(3))//20) + "颗星",result.group(4)])
    #print(result_list)
    with open(save_path,"w",newline="") as f:
        print("正在将内容存储到csv文件中...")
        writer = csv.writer(f)
        writer.writerows(result_list)
        print("完成!")


if __name__ == "__main__":
    fetch_msg(link)


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容