尝试在python上使用Selenium chrome webdriver自动化一些测试时遇到了问题。我的目标是在我提出每个请求后切换用户代理和代理服务器,以避免被禁止。这是我的代码:
from selenium import webdriver
import time
import random
from fake_useragent import UserAgent
from datetime import datetime as dt
def add_random_ua():
# Generate a random user-agent useing fake_useragent library
fake_ua = UserAgent().random
# If there is already a "user-agent" argument in options delete it
for item in options.arguments:
if '--user-agent=' in item:
options.arguments.remove(item)
# Add generated user-agent to options
options.add_argument(f'--user-agent={fake_ua}')
print(f'User-agent: {fake_ua}')
def add_random_proxy():
# Same logic as with add_random_ua
# PROXY_LIST is just a list read from .txt file
random_proxy = PROXY_LIST[random.randint(0, len(PROXY_LIST) - 1)]
for item in options.arguments:
if '--proxy-server=' in item:
options.arguments.remove(item)
options.add_argument(f'--proxy-server={random_proxy}')
print(f'Proxy-server: {random_proxy}')
chromedriver = 'C:\\Users\\User\\Desktop\\chromedriver\\chromedriver.exe'
# Initial chromedriver options
options = webdriver.ChromeOptions()
options.add_argument("--window-size=1024,768")
options.add_argument("--disable-notifications")
options.add_argument("--disable-popup-blocking")
options.add_argument("--user-data-dir=C:\\Users\\User\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument("--profile-directory=Default")
options.add_argument("--ignore-certificate-errors")
while True:
print(f'Timestamp: {dt.now().strftime("%Y-%m-%d %H:%M:%S")}')
add_random_ua()
add_random_proxy()
web = webdriver.Chrome(chromedriver, options=options)
web.implicitly_wait(30)
web.get(URL)
# Some testing code...
web.quit()
因此,脚本的基本逻辑是设置一些初始chromedriver选项,然后在while循环中添加随机代理服务器和用户代理,使用新选项创建一个webdriver实例,执行一些代码,使用.quit( ),然后再次制作所有这些东西。
主要问题是它不能与add_random_proxy()一起使用-每次由于代理连接失败而无法连接到Internet时(代理本身完全可以)。当我评论这一行时,一切正常。我在做什么错了?
谢谢!