python代码块

1
2
3
4
5
6
7
import requests
import re
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from threading import Thread # 多线程调用类
from concurrent.futures import ThreadPoolExecutor

1.滚动页面到底部

1
2
3
js = 'window.scrollTo(0,document.body.scrollHeight)'
driver.execute_script(js)
time.sleep(5)

2.自动翻页

1
2
3
4
5
6
7
for x in range(1, 6, 2):      # 自动翻页
time.sleep(3)
j = x / 9
# document.documentElement.scrollTop 指定滚动条的位置
# document.documentElement.scrollHeight 获取浏览器页面的最大高度
js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
driver.execute_script(js)

3. selenium自动化

1
2
3
4
driver = webdriver.Chrome()  # 创建浏览器
driver.get('url') # 请输入网址
driver.maximize_window() # 页面最大化
driver.implicitly_wait(10) # 隐式等待

4.下载

1
2
3
4
5
6
7
8
9
def download():
i = 0
for url1 in video_url_list:
resp_video = requests.get(url=url1).content # 转换成二进制文件
title_list[i] = title_list[i].replace("/", "-") # 转换特殊字符
with open('ZHvideo\\' + title_list[i] + '.mp4', mode='wb') as f:
f.write(resp_video) # 写入视频文件
print(title_list[i] + "下载完成!!!")
i += 1

5.ui界面

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
main_url = []  # 变量存储输入的参数
def DaoHang(): # 导航栏
app = QApplication([])

window = QMainWindow()
window.resize(1000, 100)# 窗口尺寸
window.move(500, 310)# 窗口位置
window.setWindowTitle('导航栏')

textEdit = QPlainTextEdit(window)
textEdit.setPlaceholderText("请输入网址")
textEdit.move(10, 25)# 输入框位置
textEdit.resize(800, 30)# 输入框尺寸

def show():
url = textEdit.toPlainText()# 接收输入的参数
main_url.append(url)# url参数传递到main_url全局变量中
print(main_url)
window.close()

button = QPushButton('确定', window)
button.clicked.connect(show)
button.move(850, 25)
window.show()
app.exec_()

DaoHang()# 调用函数

6.下载进度条

1
2
3
4
5
6
7
8
9
10
11
12
13
from tqdm import tqdm

resp_video = requests.get(url=video_url, stream=True)
file_size = int(resp_video.headers.get('Content-Length'))
# 初始化进度条长度
pbar = tqdm(total=file_size)
with open("video\\" + title + ".mp4", mode='wb') as f:
for chunk in resp_video.iter_content(1024*1024*2):
f.write(chunk)
pbar.set_description('正在下载中...')
pbar.update(1024*1024*2)
pbar.set_description('下载完成!!!')
pbar.close()

7.自动化读取表格

1
2
3
4
5
6
7
8
9
10
11
import xlrd
import os

# 打开excel表格(表格路径)
xlsx = xlrd.open_workbook('xl表格.xlsx')
# 获取第几个单元格
sheet = xlsx.sheet_by_index(0)
# 获取数据(行, 列)
data = sheet.cell_value(0, 0)
print(data)

8.写入表格

1
2
3
4
5
6
7
8
9
10
11
import xlwt
import os

# 新建工作薄
newWorkbook = xlwt.Workbook('utf-8')
# 创建sheet表格
Sheet = newWorkbook.add_sheet(sheetname='sheet1')
# 新建单元格,写入内容(行,列,内容)
Sheet.write(0, 0, '名字')
# 保存
newWorkbook.save('./xl表格.xlsx')