0


Selenium自动化教程(三)设置IP和UA

Selenium自动化教程(三)

Selenium自动化被拦截怎么办

一般来说,网站都有一定的保护机制。自动化程序的本意是减少机械式重复的工作内容,但要考虑到对方网站的业务能力上限有多高,避免站点将我们误认为是攻击性程序,从而影响双方正常业务。

开发时需要注意以下几点:

  • 限制程序的请求频率
  • 适时的切换IP和UA

如何设置IP和UA

先安装随机UA库

pip3 install fake-useragent

上代码:

#!/usr/bin/python# coding: UTF-8# -*- coding:utf-8 -*-# IP代理和UA切换from time import sleep

from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

from util.ProxyUtil import ProxyUtil

global driver

#  启动Chromedefget_driver():
    proxy_util = ProxyUtil()
    proxies = proxy_util.load_proxy()
    user_agent = UserAgent().random
    # 格式样式# headers请求头 --user-agent=Mxxxxxx/5.0 (Macintosh; U; Intel Mac OS X xx_x_x; de-de) AppleWebKit/xxx.xx.xx (KHTML, like Gecko) Version/5.0.4 Sxxxx/xxx.xx.xx# proxies代理设置 --proxy-server=http://xxx.xxx.xxx.xxx:80print("headers请求头",'--user-agent={}'.format(str(user_agent)))print("proxies代理设置",'--proxy-server={}'.format(str(proxies)))
    chrome_options = Options()# 设置不加载图片# prefs = {"profile.managed_default_content_settings.images": 2}# chrome_options.add_experimental_option("prefs", prefs)# 设置代理
    chrome_options.add_argument('--proxy-server={}'.format(str(proxies)))# 替换User-Agent
    chrome_options.add_argument('--user-agent={}'.format(str(user_agent)))# 配置为自己设置的UA

    service = Service(r'../util/chromedriver')# 启动Chromereturn webdriver.Chrome(service=service, chrome_options=chrome_options)if __name__ =='__main__':try:
        driver = get_driver()
        driver.get('http://httpbin.org/ip')# 显性等待
        WebDriverWait(driver,10).until(lambda_: driver.find_element(By.XPATH,'/html/body/pre'))print("页面代理设置", driver.page_source)
        sleep(1000)except Exception as e:
        driver.quit()print('open_url:', e)

ProxyUtil的下载地址
也可以按照上面格式,填入自己的代理信息

代码执行后可以看到代理是否正确配置:
在这里插入图片描述

按F12可以看到UA的状态
在这里插入图片描述


本文转载自: https://blog.csdn.net/qq_25812615/article/details/129688150
版权归原作者 Ssoul、肥鱼 所有, 如有侵权,请联系我们删除。

“Selenium自动化教程(三)设置IP和UA”的评论:

还没有评论