Python에서 프록시로 Selenium Webdriver 실행
몇 가지 기본 작업을 수행하기 위해 Python에서 Selenium Webdriver 스크립트를 실행하려고합니다. Selenium IDE 인터페이스를 통해 로봇을 실행할 때 로봇이 완벽하게 작동하도록 할 수 있습니다 (예 : 단순히 GUI가 내 작업을 반복하도록 할 때). 그러나 코드를 Python 스크립트로 내보내고 명령 줄에서 실행하려고하면 Firefox 브라우저가 열리지 만 시작 URL에 액세스 할 수 없습니다 (명령 줄에 오류가 반환되고 프로그램이 중지됨). 이것은 내가 액세스하려는 웹 사이트 등에 관계없이 발생합니다.
여기에는 데모 용으로 매우 기본적인 코드가 포함되어 있습니다. 반환되는 오류가 프록시에서 생성 된 것처럼 보이기 때문에 코드의 프록시 섹션을 올바르게 포함했다고 생각하지 않습니다.
어떤 도움이라도 대단히 감사하겠습니다.
아래 코드는 단순히 www.google.ie를 열고 "selenium"이라는 단어를 검색하기위한 것입니다. 나를 위해 그것은 빈 파이어 폭스 브라우저를 열고 중지합니다.
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()
이런 건 어때
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)
여기에서 자세한 내용을 읽을 수 있습니다 .
이 방식으로 작동합니다 (@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)
내 솔루션 :
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 프로필이 제대로 포트로 설정되지 않고 프록시를 통한 연결이 작동하지 않습니다.
누구든지 해결책을 찾고 있다면 방법은 다음과 같습니다.
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/')
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 )프로그램에서 전화 하십시오.
FirefoxProfile을 설정하여 시도
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")
This program tested on both Windows 8 and Mac OSX. If you are using Mac OSX and if you don't have selenium updated then you may face selenium.common.exceptions.WebDriverException. If so, then try again after upgrading your selenium
pip install -U selenium
The result stated above may be correct, but isn't working with the latest webdriver. Here is my solution for the above question. Simple and sweet
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)
Proxy with verification. This is a whole new python script in reference from a Mykhail Martsyniuk sample script.
# 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/")
try running tor service, add the following function to your code.
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()
As stated by @Dugini, some config entries have been removed. Maximal:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
ReferenceURL : https://stackoverflow.com/questions/17082425/running-selenium-webdriver-with-a-proxy-in-python
'IT TIP' 카테고리의 다른 글
| itertools에서 chain과 chain.from_iterable의 차이점은 무엇입니까? (0) | 2020.12.25 |
|---|---|
| PHP에서 시간이 두 시간 사이인지 확인하는 방법 (0) | 2020.12.25 |
| 관계형 데이터베이스가 Node.js에 적합하지 않습니까? (0) | 2020.12.25 |
| angularjs에서 우리는 ng-disabled 지시문을 가지고 있는데, ng-show와 ng-hide를 가지고 있기 때문에 프레임 워크에서 ng-enabled 지시문을 제공하지 않는 이유 (0) | 2020.12.25 |
| decltype 동작의 근거는 무엇입니까? (0) | 2020.12.25 |