selenium无头方式的优化--推荐使用

更新了一些新的内容,去掉报错提示

1.添加cookie

2.添加 proxy

3.封装函数

import time

from selenium import webdriver

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By


def wutoubrowser():
    # 定义chrome驱动去地址
    devce_path = Service('./chromedriver.exe')

    # 创建Chrome浏览器设置变量
    chrome_options = Options()
    # 无界面模式
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')


    # 设置浏览器窗口大小
    chrome_options.add_argument('--window-size=1920,1080')
    # 添加代理
    # chrome_options.add_argument("--proxy-server=http://" + ip:port)

    # chrome_options.add_argument("--proxy-server=http://112.87.140.163:9443")

    # 修改User-Agent
    chrome_options.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46"')
    # 禁用图片
    chrome_options.add_argument('blink-settings=imagesEnabled=false')
    # 实例化Chrome driver
    bro = webdriver.Chrome(service=devce_path, options=chrome_options)

    # 返回一个浏览器
    return bro

bro = wutoubrowser()
# 打开百度
bro.get("https://www.baidu.com/")

# print(bro.page_source)

# 在百度搜索框中输入  “壁纸”
search_input_baidu = bro.find_element(By.ID, "kw")

search_input_baidu.send_keys("壁纸")
time.sleep(2)
# 找到  百度一下的 按钮
button = bro.find_element(By.ID, "su")

button.click()
time.sleep(2)

# 滑到屏幕的底部
js_bottom = 'document.documentElement.scrollTop=100000'
bro.execute_script(js_bottom)
time.sleep(2)
#
# 获取下一页的 按钮
next = bro.find_element(By.XPATH, '//a[@class="n"]')

next.click()
time.sleep(2)

# 滑到屏幕的底部
js_bottom = 'document.documentElement.scrollTop=100000'
bro.execute_script(js_bottom)
time.sleep(2)

# 保存快照信息,确认是否进行了操作
bro.save_screenshot('newbaidu.png')

bro.quit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值