[Selenium] 添加随机agent

发布时间 2023-06-15 16:48:08作者: *飞飞*
Agents = [' (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d',
        ' (Windows NT 5.1; U; en; rv:1.9.1.6) Gecko/20091201',
        ' (X11; U; Linux x86_64; fr; rv:1.9.0.11) Gecko/2009060309 Ubuntu/9.04 (jaunty)',
        ' (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0;(compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3; Tablet PC 2.0)',
        ' (Windows NT 10.0; Win64; x64)',
        ' (compatible; MSIE 6.0; X11; Linux i686; en)']

def driver_init():
  option = webdriver.ChromeOptions()
  #防浏览器关闭
  option.add_experimental_option('detach', True)
  #防 ssl 报错
  option.add_argument('--ignore-certificate-errors')
  option.add_argument('--ignore-ssl-errors')
  headers = {'User-Agent':UserAgent().random}
  headers = {'User-Agent':'Chrome'+Agents[random.randint(0,5)]}
  print(headers)
  option.add_argument('User-Agent={}'.format(headers['User-Agent']))
  #option.add_argument('--proxy-server=http://%s' % proxy)
  option.add_experimental_option('excludeSwitches',['enable-logging'])
  driver = webdriver.Chrome(options=option)
  driver.delete_all_cookies()