import os
from time import sleep
import tkinter.messagebox
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
def Save_Comment(views):
filedir="G:/python3.6/0.python的材料/7.词云3/"
TextName="1.txt"
if not os.path.exists(filedir):
os.mkdir(filedir)
with open(filedir+TextName,mode="w",encoding="utf-8") as f:
f.write(views)
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15"
opt = webdriver.ChromeOptions()
opt.add_experimental_option('excludeSwitches', ['enable-automation'])
opt.add_argument('--user-agent=%s' % user_agent)
#禁止图片和css加载
prefs = {"profile.managed_default_content_settings.images": 2,'permissions.default.stylesheet':2}
opt.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=opt)
#1.zhuantiao1
driver.maximize_window()
driver.implicitly_wait(30)
url="https://www.bilibili.com/video/av47441335?from=search&seid=1115311873749794500"
driver.get(url)
sleep(7)
views=''
page=1
for counts in range(100):
print("第%d页收集开始---------------->"%page)
command=driver.find_elements_by_class_name("text")
sleep(4)
for i in command:
view=i.get_attribute('textContent')
views+=view+"\n"
print(i.get_attribute('textContent'))
try:
driver.find_element_by_link_text("下一页").click()
print("第%d页收集完成---------------->"%page)
page+=1
sleep(4)
except:
Save_Comment(views)
break
selenium爬取b站评论
最新推荐文章于 2024-09-18 21:55:52 发布
本文介绍了一种使用Python的Selenium库爬取Bilibili网站特定视频评论的方法,并将评论数据保存到本地文件中。通过设置浏览器选项,禁用图片和CSS加载,优化网页加载速度,从而提高爬虫效率。
摘要由CSDN通过智能技术生成