Python에서 프록시와 함께 Selenium 웹 드라이버 실행
저는 몇 가지 기본적인 작업을 하기 위해 파이썬에서 셀레늄 웹 드라이버 스크립트를 실행하려고 합니다.셀레늄 IDE 인터페이스를 통해 로봇을 실행할 때(즉, GUI가 내 작업을 반복하도록 할 때) 로봇이 완벽하게 작동하도록 할 수 있습니다.그러나 Python 스크립트로 코드를 내보내고 명령줄에서 실행하려고 하면 Firefox 브라우저가 열리지만 시작 URL에 액세스할 수 없습니다(명령줄로 오류가 반환되고 프로그램이 중지됨).내가 어떤 웹사이트에 접속하려고 하는지 등에 관계없이 이런 일이 발생합니다.
여기에 시연용으로 매우 기본적인 코드를 포함했습니다.반환되는 오류가 프록시에 의해 발생하는 것 같아 코드의 프록시 섹션을 제대로 포함하지 못한 것 같습니다.
어떤 도움이라도 주시면 대단히 감사하겠습니다.
아래 코드는 단순히 www.google.ie 을 열고 "셀레늄"이라는 단어를 검색하기 위한 것입니다.저는 빈 파이어폭스 브라우저를 열고 멈춥니다.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
from selenium.webdriver.common.proxy import *
class Testrobot2(unittest.TestCase):
def setUp(self):
myProxy = "http://149.215.113.110:70"
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy,
'sslProxy': myProxy,
'noProxy':''})
self.driver = webdriver.Firefox(proxy=proxy)
self.driver.implicitly_wait(30)
self.base_url = "https://www.google.ie/"
self.verificationErrors = []
self.accept_next_alert = True
def test_robot2(self):
driver = self.driver
driver.get(self.base_url + "/#gs_rn=17&gs_ri=psy-ab&suggest=p&cp=6&gs_id=ix&xhr=t&q=selenium&es_nrs=true&pf=p&output=search&sclient=psy-ab&oq=seleni&gs_l=&pbx=1&bav=on.2,or.r_qf.&bvm=bv.47883778,d.ZGU&fp=7c0d9024de9ac6ab&biw=592&bih=665")
driver.find_element_by_id("gbqfq").clear()
driver.find_element_by_id("gbqfq").send_keys("selenium")
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException, e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
다음과 같은 방식으로 작동합니다(@Amey 및 @user4642224 코드와 비슷하지만 조금 더 짧음).
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = "ip_addr:port"
prox.socks_proxy = "ip_addr:port"
prox.ssl_proxy = "ip_addr:port"
capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)
driver = webdriver.Chrome(desired_capabilities=capabilities)
이런 거 어때요?
PROXY = "149.215.113.110:70"
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":None,
"proxyType":"MANUAL",
"class":"org.openqa.selenium.Proxy",
"autodetect":False
}
# you have to use remote, otherwise you'll have to code it yourself in python to
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)
당신은 여기에서 그것에 대해 더 읽을 수 있습니다.
내 솔루션:
def my_proxy(PROXY_HOST,PROXY_PORT):
fp = webdriver.FirefoxProfile()
# Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
print PROXY_PORT
print PROXY_HOST
fp.set_preference("network.proxy.type", 1)
fp.set_preference("network.proxy.http",PROXY_HOST)
fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
fp.set_preference("general.useragent.override","whater_useragent")
fp.update_preferences()
return webdriver.Firefox(firefox_profile=fp)
그런 다음 코드를 불러옵니다.
my_proxy(PROXY_HOST,PROXY_PORT)
문자열을 포트 #:로 전달하는 중에 이 코드에 문제가 발생했습니다.
PROXY_PORT="31280"
이것은 중요합니다.
int("31280")
문자열 대신 정수를 전달해야 합니다. 그렇지 않으면 Firefox 프로파일이 올바른 포트로 설정되지 않고 프록시를 통한 연결이 작동하지 않습니다.
이 문서는 꽤 오래된 게시물이지만, 다른 사람들에게는 오늘날에도 여전히 답을 제공함으로써 도움이 될 수 있으며, 원래 작성자는 작업 해결책에 매우 가까웠습니다.
우선 ftpProxy 설정은 현재 더 이상 지원되지 않으며 오류가 발생합니다.
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy, # this will throw an error
'sslProxy': myProxy,
'noProxy':''})
다음으로 프록시 속성을 설정하는 대신 다음과 같은 파이어폭스 옵션을 사용해야 합니다.
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'sslProxy': myProxy,
'noProxy': ''})
options = Options()
options.proxy = proxy
driver = webdriver.Firefox(options=options)
또한 프록시를 지정할 때 특히 여러 프로토콜에 대해 동일한 프록시를 사용하려는 경우에는 체계를 정의하지 마십시오.
myProxy = "149.215.113.110:70"
전체적으로 이렇게 보입니다.
from selenium import webdriver
from selenium.webdriver.common.proxy import *
from selenium.webdriver.firefox.options import Options
myProxy = "149.215.113.110:70"
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'sslProxy': myProxy,
'noProxy': ''})
options = Options()
options.proxy = proxy
driver = webdriver.Firefox(options=options)
driver.get("https://www.google.ie")
프록시(검증 포함).이것은 Mykhail Martsyniuk 샘플 스크립트에서 참조된 완전히 새로운 파이썬 스크립트입니다.
# Load webdriver
from selenium import webdriver
# Load proxy option
from selenium.webdriver.common.proxy import Proxy, ProxyType
# Configure Proxy Option
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
# Proxy IP & Port
prox.http_proxy = “0.0.0.0:00000”
prox.socks_proxy = “0.0.0.0:00000”
prox.ssl_proxy = “0.0.0.0:00000”
# Configure capabilities
capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)
# Configure ChromeOptions
driver = webdriver.Chrome(executable_path='/usr/local/share chromedriver',desired_capabilities=capabilities)
# Verify proxy ip
driver.get("http://www.whatsmyip.org/")
sock5 프록시도 설정해 보십시오.나도 같은 문제에 직면했고 양말 프록시를 사용하면 해결됩니다.
def install_proxy(PROXY_HOST,PROXY_PORT):
fp = webdriver.FirefoxProfile()
print PROXY_PORT
print PROXY_HOST
fp.set_preference("network.proxy.type", 1)
fp.set_preference("network.proxy.http",PROXY_HOST)
fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
fp.set_preference("network.proxy.https",PROXY_HOST)
fp.set_preference("network.proxy.https_port",int(PROXY_PORT))
fp.set_preference("network.proxy.ssl",PROXY_HOST)
fp.set_preference("network.proxy.ssl_port",int(PROXY_PORT))
fp.set_preference("network.proxy.ftp",PROXY_HOST)
fp.set_preference("network.proxy.ftp_port",int(PROXY_PORT))
fp.set_preference("network.proxy.socks",PROXY_HOST)
fp.set_preference("network.proxy.socks_port",int(PROXY_PORT))
fp.set_preference("general.useragent.override","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A")
fp.update_preferences()
return webdriver.Firefox(firefox_profile=fp)
그럼 전화해요install_proxy ( ip , port )
사용자 프로그램에서.
솔루션을 찾고 있는 사람이 있다면 다음과 같은 방법을 참조하십시오.
from selenium import webdriver
PROXY = "YOUR_PROXY_ADDRESS_HERE"
webdriver.DesiredCapabilities.FIREFOX['proxy']={
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":None,
"proxyType":"MANUAL",
"autodetect":False
}
driver = webdriver.Firefox()
driver.get('http://www.whatsmyip.org/')
위에 언급된 결과는 정확할 수 있지만 최신 웹 드라이버에서는 작동하지 않습니다.위의 질문에 대한 나의 해결책이 있습니다.심플하고 달콤한
http_proxy = "ip_addr:port"
https_proxy = "ip_addr:port"
webdriver.DesiredCapabilities.FIREFOX['proxy']={
"httpProxy":http_proxy,
"sslProxy":https_proxy,
"proxyType":"MANUAL"
}
driver = webdriver.Firefox()
OR
http_proxy = "http://ip:port"
https_proxy = "https://ip:port"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
}
driver = webdriver.Firefox(proxy=proxyDict)
Firefox 프로필을 설정하여 시도합니다.
from selenium import webdriver
import time
"Define Both ProxyHost and ProxyPort as String"
ProxyHost = "54.84.95.51"
ProxyPort = "8083"
def ChangeProxy(ProxyHost ,ProxyPort):
"Define Firefox Profile with you ProxyHost and ProxyPort"
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", ProxyHost )
profile.set_preference("network.proxy.http_port", int(ProxyPort))
profile.update_preferences()
return webdriver.Firefox(firefox_profile=profile)
def FixProxy():
""Reset Firefox Profile""
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 0)
return webdriver.Firefox(firefox_profile=profile)
driver = ChangeProxy(ProxyHost ,ProxyPort)
driver.get("http://whatismyipaddress.com")
time.sleep(5)
driver = FixProxy()
driver.get("http://whatismyipaddress.com")
이 프로그램은 Windows 8과 Mac OS X 모두에서 테스트되었습니다.Mac OSX를 사용하고 있고 셀레늄이 업데이트되지 않은 경우 다음과 같은 상황이 발생할 수 있습니다.selenium.common.exceptions.WebDriverException
, 해 보세요.
pip install -U selenium
이것은 2022년 9월에 도움이 됩니다 - Auth user+password로 셀레늄을 위한 프록시.
import os
import zipfile
from selenium import webdriver
PROXY_HOST = '192.168.3.2' # rotating proxy or host
PROXY_PORT = 8080 # port
PROXY_USER = 'proxy-user' # username
PROXY_PASS = 'proxy-password' # password
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = """
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "%s",
port: parseInt(%s)
},
bypassList: ["localhost"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "%s",
password: "%s"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
""" % (PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS)
def get_chromedriver(use_proxy=False, user_agent=None):
path = os.path.dirname(os.path.abspath(__file__))
chrome_options = webdriver.ChromeOptions()
if use_proxy:
pluginfile = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(pluginfile, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
chrome_options.add_extension(pluginfile)
if user_agent:
chrome_options.add_argument('--user-agent=%s' % user_agent)
driver = webdriver.Chrome(
os.path.join(path, 'chromedriver'),
chrome_options=chrome_options)
return driver
def main():
driver = get_chromedriver(use_proxy=True)
driver.get('https://ifconfig.me/)
if __name__ == '__main__':
main()
위와 이 질문에 대한 답변은 Linux에서 Selenium 3.14 및 Firefox 68.9를 사용하는 경우에 적합하지 않거나 불필요하게 복잡합니다.WPAD 구성을 사용해야 했습니다. 때로는 프록시 뒤에서(VPN에서), 때로는 그렇지 않았습니다.코드를 조금 연구한 후, 저는 다음과 같은 생각을 해냈습니다.
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
proxy = Proxy({'proxyAutoconfigUrl': 'http://wpad/wpad.dat'})
profile = FirefoxProfile()
profile.set_proxy(proxy)
driver = webdriver.Firefox(firefox_profile=profile)
프록시 초기화는 proxyType을 ProxyType으로 설정합니다.부작용으로 PAC(URL에서 자동 구성)를 사용할 수 있습니다.
또한 다음을 사용하여 Firefox의 자동 탐지 기능과 함께 작동했습니다.
from selenium.webdriver.common.proxy import ProxyType
proxy = Proxy({'proxyType': ProxyType.AUTODETECT})
그러나 WPAD처럼 내부 URL(프록시되지 않음)과 외부 URL(프록시됨) 모두에서 작동하지 않을 것이라고 생각합니다.수동 구성에서도 유사한 프록시 설정이 작동해야 합니다.가능한 프록시 설정은 여기 코드에서 확인할 수 있습니다.
를 Proxy로 합니다.proxy=proxy
운전자에게는 작동하지 않습니다. 허용되지만 무시됩니다. (권장 금지 경고가 있어야 하지만 제 경우 행동이 삼키고 있다고 생각합니다.).
이것은 저에게 효과가 있었고 헤드리스 브라우저를 사용할 수 있게 해주므로 프록시를 통과하는 메소드를 호출하기만 하면 됩니다.
def setProxy(proxy):
options = Options()
options.headless = True
#options.add_argument("--window-size=1920,1200")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = proxy
prox.ssl_proxy = proxy
capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)
return webdriver.Chrome(desired_capabilities=capabilities, options=options, executable_path=DRIVER_PATH)
인증된 프록시를 사용하는 예가 없어서 놀랐습니다.
인증된 프록시(Firefox & Chrome)를 위한 2022년 10월 솔루션:
from selenium import webdriver
PROXY_HOST = "0.0.0.0";
PROXY_PORT = "0000"
PROXY_USERNAME = "user"
PROXY_PASS = "pass"
# If you're using Firefox
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http",PROXY_HOST)
profile.set_preference("network.proxy.http_port", PROXY_PORT)
fp.set_preference('network.proxy.no_proxies_on', 'localhost, 127.0.0.1')
credentials = '%s:%s' % (PROXY_USERNAME, PROXY_PASS)
credentials = b64encode(credentials.encode('ascii')).decode('utf-8')
fp.set_preference('extensions.closeproxyauth.authtoken', credentials)
driver = webdriver.Firefox(firefox_profile=profile)
# If you're using Chrome
chrome_options = WebDriver.ChromeOptions()
options.add_argument('--proxy-server=http://%s:%s@%s:%s' % (PROXY_HOST, PROXY_PORT, PROXY_USERNAME, PROXY_PASS))
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
# Proxied request
driver.get("https://www.google.com")
@Dugini에서 설명한 것처럼 일부 구성 항목이 제거되었습니다.최대:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
모든 온라인 소스에서 데이터를 스크랩하는 것은 스크랩 API를 사용할 때 매우 쉽습니다.스크레이퍼 API를 사용하여 웹 페이지에서 정보를 긁어내면 자동으로 웹 데이터를 구문 분석할 수 있습니다.API를 소스 코드에 통합할 수도 있습니다.API를 사용하여 데이터를 긁어내는 것 외에, 당신은 CSS 선택기를 사용하여 데이터를 긁어내는 아름다운 수프에 아래 언급된 소스 코드를 시도할 수 있습니다.이 코드를 시도하기 전에 select() 메서드를 사용하여 여러 요소를 찾을 수 있습니다.이와 함께 단일 요소 검색에 사용할 _one()을 선택합니다.
소스 코드:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
PROXY = "177.46.141.143:59393" #your proxy (ip address: port no)
chrome_options = WebDriverWait.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
chrome = webdriver.Chrome(chrome_options=chrome_options)
chrome.get("https://www.ipchicken.com/")
Firefox용 인증 및 SSL이 포함된 2023년 1월 솔루션
from selenium import webdriver
PROXY_HOST = "ip"
PROXY_PORT = "port"
PROXY_USERNAME = "username"
PROXY_PASS = "password"
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference('network.proxy.ssl_port', int(PROXY_PORT))
profile.set_preference('network.proxy.ssl', PROXY_HOST)
profile.set_preference("network.proxy.http", PROXY_HOST)
profile.set_preference("network.proxy.http_port", int(PROXY_PORT))
profile.set_preference("network.proxy.no_proxies_on", 'localhost, 127.0.0.1')
profile.set_preference("network.proxy.socks_username", PROXY_USERNAME)
profile.set_preference("network.proxy.socks_password", PROXY_PASS)
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)
driver.get("https://2ip.ru")
또한 프록시 공급자 계정 설정에서 IP 주소를 잠가야 할 수도 있습니다.그렇지 않으면 페이지 로드 시 자격 증명을 입력하라는 메시지가 표시됩니다.
tor 서비스를 실행해 보십시오. 코드에 다음 기능을 추가하십시오.
def connect_tor(port):
socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port, True)
socket.socket = socks.socksocket
def main():
connect_tor()
driver = webdriver.Firefox()
언급URL : https://stackoverflow.com/questions/17082425/running-selenium-webdriver-with-a-proxy-in-python
'programing' 카테고리의 다른 글
두 커밋을 하나의 커밋으로 결합하려면 어떻게 해야 합니까? (0) | 2023.08.25 |
---|---|
도커에서 저장과 내보내기의 차이점은 무엇입니까? (0) | 2023.08.25 |
Javascript를 사용하여 인쇄 대화 상자를 팝업하려면 어떻게 해야 합니까? (0) | 2023.08.25 |
스레드 메시징 시스템 데이터베이스 스키마 설계 (0) | 2023.08.25 |
장치 픽셀 비율은 정확히 무엇입니까? (0) | 2023.08.25 |