由于百度云盘共享文件需要验证链接有效性,因此需要使用selenium模拟浏览器操作来获取链接有效性。

以下是爬取百度云盘共享文件并输出到excel表格的详细代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import xlwt

# 设置chromedriver的路径
chrome_options = Options()
chrome_options.add_argument('--headless')  # 无头模式,不打开浏览器
driver = webdriver.Chrome(executable_path='chromedriver.exe', options=chrome_options)

url = 'https://pan.baidu.com/s/1C1uX9iSU2eLbD0w3Tq1dJw'
driver.get(url)

# 等待网页加载完成
time.sleep(5)

# 点击验证按钮
verify_button = driver.find_element_by_class_name('verify-btn')
verify_button.click()

# 等待验证弹窗加载完成
time.sleep(5)

# 模拟滑动验证
slider_button = driver.find_element_by_class_name('JDJRV-slide-btn')
ActionChains(driver).click_and_hold(slider_button).perform()
ActionChains(driver).move_by_offset(260, 0).perform()
ActionChains(driver).release().perform()

# 等待验证通过
time.sleep(10)

# 获取文件名称和链接
file_name = driver.find_element_by_class_name('file-title').text
file_link = driver.find_element_by_class_name('pickpw').text.strip()

# 验证链接是否有效
driver.get(file_link)
time.sleep(5)
if driver.current_url == 'https://pan.baidu.com/error/404.html':
    print('链接无效')
else:
    print(f'文件名:{file_name}\n链接地址:{file_link}')

    # 输出到excel表格
    workbook = xlwt.Workbook(encoding='utf-8')
    sheet = workbook.add_sheet('Sheet1')
    sheet.write(0, 0, '文件名')
    sheet.write(0, 1, '链接地址')
    sheet.write(1, 0, file_name)
    sheet.write(1, 1, file_link)
    workbook.save('file_links.xls')

# 关闭浏览器
driver.quit()

在代码中,首先使用selenium模拟浏览器访问百度云盘共享文件的页面,并等待页面加载完成。然后点击验证按钮,并等待验证弹窗加载完成。接着使用模拟滑动验证的方法来通过验证。等待验证通过后,获取文件名称和链接。然后再次使用selenium模拟访问链接,判断链接是否有效。最后将文件名称和链接输出到excel表格中。最后关闭浏览器。

用python爬取百度云盘共享文件并且验证链接有效性后输出文件名称和地址到excel表格列出详细代码

原文地址: https://www.cveoy.top/t/topic/hco 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录