代码拉取完成,页面将自动刷新
import time
import requests
from selenium import webdriver
import json
from bs4 import BeautifulSoup
import random
def get_cookies():
url = 'https://www.bilibili.com'
driver.get(url)
driver.delete_all_cookies() # 先删除cookies
time.sleep(20)
dictcookies = driver.get_cookies() # 读取登录之后浏览器的cookies
jsoncookies = json.dumps(dictcookies) # 将字典数据转成json数据便于保存
with open('cookie.txt', 'w') as f: # 写进文本保存
f.write(jsoncookies)
print('cookies is ok')
def add_cookie():
f = open('cookie.txt', 'r')
listcookie = json.loads(f.read()) # 读取文件中的cookies数据
for cookie in listcookie:
driver.add_cookie(cookie) # 将cookies数据添加到浏览器
def open_page(mid, page):
url = "http://api.bilibili.com/x/relation/followers?vmid=" + mid + "&pn=" + str(
page + 1) + "&ps=50&order=desc&jsonp=jsonp"
print(url)
driver.get(url)
html = driver.execute_script("return document.documentElement.outerHTML") # 必须执行js
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')
fans_data = str(soup.text)
num = fans_data.count("uname")
for i in range(0,num):
a = fans_data.find("uname")
b = fans_data.find("face")
c = fans_data.find("track_id")
d = fans_data.find("mid")
e = fans_data.find("attribute")
fans_list.append(fans_data[a+8:b-3])
mid_list.append(fans_data[d+5:e-2])
fans_data=str(fans_data[c+10:])
def get_nums():
url_quantity = "https://api.bilibili.com/x/relation/stat?vmid="+uid+"&jsonp=jsonp" #查询粉丝数量网址
header_quantity={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"}
res_quantity=requests.get(url=url_quantity,headers=header_quantity)
p = res_quantity.text.find("follower")
fans_quantity = int(res_quantity.text[p+10:len(res_quantity.text) - 2])
print("粉丝数量:"+str(fans_quantity))
return fans_quantity
fans_list = []
mid_list = []
driver = webdriver.Edge()
get_cookies()
add_cookie()
uid = str(51903854)
nums_prev = get_nums()
fans_quantity = nums_prev
print('Start!')
while fans_quantity <= nums_prev:
time.sleep(1)
fans_quantity = get_nums()
print('waiting...')
seed = int(time.time())
random.seed(seed)
print("该用户粉丝共", fans_quantity, "个,所有粉丝信息如下:")
pagemax = int(fans_quantity/50)+1
page_num = pagemax
for i in range(0, page_num):
open_page(uid, i)
time.sleep(2)
print(fans_list, len(fans_list))
print(mid_list, len(mid_list))
lucky = random.randint(0,100)
print("The lucky number:", lucky)
print("粉丝mid:",mid_list[lucky])
print("粉丝id:",fans_list[lucky])
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。