1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
| import csv import json import time import random import codecs import urllib import requests import threading from bs4 import BeautifulSoup from selenium import webdriver from fake_useragent import UserAgent
biliFoodUrls = [ 'https://www.bilibili.com/v/food', 'https://www.bilibili.com/v/food/make', 'https://www.bilibili.com/v/food/rural', 'https://www.bilibili.com/v/food/record', 'https://www.bilibili.com/v/food/detective', 'https://www.bilibili.com/v/food/measurement', 'https://www.bilibili.com/v/popular/rank/food' ]
def grabVideoUrl(url, videoUrls, upUrls, upUids, upInfos, browser): if not url: return if url[0] == '/': url = 'https:'+url if 'bilibili.com/video' in url: videoUrls.append(url) print(f'捕获到视频url:\t{url}') elif 'space.bilibili.com' in url: upUrls.append(url) print(f'捕获到up主url:\t{url}')
def getVideosUrl(videoUrls, upUrls, upUids, upInfos, browser): for web in biliFoodUrls: print(f"开始处理页面:\t{web}") browser.get(web) html = browser.page_source webBf = BeautifulSoup(html, 'html.parser') al = webBf.find_all("a") for a in al: url = a.get('href') args = (url, videoUrls, upUrls, upUids, upInfos, browser) video_thread = threading.Thread(target=grabVideoUrl, args=args) video_thread.start()
def grabUpsUrl(videoUrl, videoUrls, upUrls, upUids, upInfos, browser): print(f"开始处理视频url:\t{videoUrl}") headers = { 'User-Agent': UserAgent().random, 'Upgrade-Insecure-Requests': '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8', } html = requests.request('GET', videoUrl, headers=headers).content webBf = BeautifulSoup(html, "html.parser") upDiv = webBf.find(id='v_upinfo') if not upDiv: print(f"获取视频up主信息遭到拦截\t{videoUrl}") return upUrl = upDiv.find_all('a')[0].get('href') if upUrl[0] == '/': upUrl = 'https:' + upUrl upUrls.append(upUrl) print(f'捕获到up主url:\t{upUrl}')
def getUpsUrl(videoUrls, upUrls, upUids, upInfos, browser): for videoUrl in videoUrls: args = (videoUrl, videoUrls, upUrls, upUids, upInfos, browser) upUrl_thread = threading.Thread(target=grabUpsUrl, args=args) upUrl_thread.start()
def getUpsId(videoUrls, upUrls, upUids, upInfos, browser): for upUrl in upUrls: if not upUrl: continue upUid = upUrl.split("#")[0].split('/')[-1] upUids.append(upUid) print(f'捕获到up主id:\t{upUid}')
def getUpsInfo(videoUrls, upUrls, upUids, upInfos, browser): api = 'https://api.bilibili.com/x/web-interface/card?jsonp=jsonp&mid=' ids = set(upUids) upUids = list(ids)
for index, upUid in enumerate(upUids):
print(f"开始处理mid:{upUid}\t进度:{index+1}/{len(upUids)}")
headers = { 'User-Agent': UserAgent().random, 'Upgrade-Insecure-Requests': '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8', }
res = requests.request('GET', f"{api}{upUid}", headers=headers) data = res.json()['data'] n = 0
while((not data) and n < 100): print(f"请求遭到服务器拦截 重试第{n+1}次中...\t总进度:{index+1}/{len(upUids)}") headers = { 'User-Agent': UserAgent().random, 'Upgrade-Insecure-Requests': '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8', } res = requests.request('GET', f"{api}{upUid}", headers=headers) n += 1 data = res.json()['data']
if n == 100: continue
print(f"读取up主信息(mid={upUid})成功")
upName = data['card']['name'] follower = data['follower'] mid = data['card']['mid'] upInfos.append({'id': upName, 'follower': follower, 'mid': mid})
upInfos = sorted(upInfos, key=lambda upInfo: upInfo['follower'])
print("写入Excel文件中...") filename = "bili.csv" bili_csv = codecs.open(filename, 'ab', "gbk") bili_csv_writer = csv.writer(bili_csv)
for upInfo in upInfos: msg = f"写入中\tUp主id:{upInfo['id']}\t粉丝数:{upInfo['follower']}\tmid={upInfo['mid']}" print(msg)
info = (upInfo['id'], upInfo['follower'], upInfo['mid']) try: bili_csv_writer.writerow(info) except: continue
bili_csv.close()
print(f"写入到{filename}完成 本次共爬取到{len(upInfos)}个up主信息")
def main(browser): videoUrls = [] upUrls = [] upUids = [] upInfos = [] getVideosUrl(videoUrls, upUrls, upUids, upInfos, browser) getUpsUrl(videoUrls, upUrls, upUids, upInfos, browser) time.sleep(20) getUpsId(videoUrls, upUrls, upUids, upInfos, browser) getUpsInfo(videoUrls, upUrls, upUids, upInfos, browser)
if __name__ == '__main__': browser = webdriver.Chrome() for i in range(100): print(f"开始第{i+1}次爬取...") main(browser) browser.close()
|