python3爬蟲實(shí)例(三)-bs4抓取 就愛廣場(chǎng)舞舞隊(duì)名單存儲(chǔ)為csv文件

運(yùn)行版本:
Python 3.7.0
完整代碼如下:

# -*- coding: utf-8 -*-
"""
@author:lee
@create_time:2018/10/25 14:41
"""
import requests
from bs4 import BeautifulSoup
import  bs4
import csv
import time

def gethtml(url,headers):
    response =  requests.get(url,headers=headers)
    try:
        if response.status_code == 200:
            print('抓取成功網(wǎng)頁長度:',len(response.text))
            response.encoding = 'utf-8'
            return response.text
    except BaseException as e:
        print('抓取出現(xiàn)錯(cuò)誤:',e)

def get_list(html,list):
    soup = BeautifulSoup(html,'lxml')
    for zimu in soup.find_all(attrs={'id':'zimu_content'}):
        for a in zimu.find_all('a'):
            list.append(a.string)

    print(list)

def write_file(data):
    m = len(data)
    with open('wudui.csv','w',newline='') as f:
        for i in data:
            writer = csv.writer(f)
            writer.writerow([i]) #更改后不再占用多個(gè)單元格

if __name__ == '__main__':
    url = 'http://www.9igcw.com/wudui/'
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}
    list = []
    html = gethtml(url,headers)
    get_list(html,list)
    write_file(list)

運(yùn)行結(jié)果:

圖片.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容