我正在尝试在 Python 中运行 Selenium Webdriver 脚本来执行一些基本任务。通过 Selenium IDE 接口运行机器人时,我可以让机器人完美运行(即:当简单地让 GUI 重复我的操作时)。但是,当我将代码导出为 Python 脚本并尝试从命令行执行它时,Firefox 浏览器将打开但无法访问起始 URL(向命令行返回错误并且程序停止)。无论我尝试访问什么网站等,我都会发生这种情况。
出于演示目的,我在这里包含了一个非常基本的代码。我认为我没有正确包含代码的代理部分,因为返回的错误似乎是由代理生成的。
任何帮助将不胜感激。
下面的代码只是为了打开 www.google.ie 并搜索单词“selenium”。对我来说,它会打开一个空白的 Firefox 浏览器并停止。
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)
您可以阅读有关它的更多信息here。
webdriver.DesiredCapabilities.EDGE['proxy']
无效,因为 Microsoft Edge 当前没有配置代理服务器的设置(要将 Edge 与代理一起使用,您必须在 Windows 网络下配置代理连接设置)。
我的解决方案:
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 配置文件将不会设置为正确的端口,并且通过代理的连接将无法正常工作。
Proxy()
类与 FirefoxProfile()
类混淆了。使用配置文件首选项,您必须分别传递 ip 和端口,并将 port
转换为 int()
。在 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/')
也尝试设置 sock5 代理。我遇到了同样的问题,通过使用 socks 代理解决了
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 )
。
带验证的代理。这是一个全新的 Python 脚本,来自 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/")
这是一篇相当老的帖子,但是,对于其他人来说,它可能仍然可以通过提供今天的答案而受益,但最初的作者非常接近一个可行的解决方案。
首先,此时不再支持ftpProxy设置,会报错
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy, # this will throw an error
'sslProxy': myProxy,
'noProxy':''})
接下来,您应该使用 firefox 选项,而不是设置代理属性
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")
上述结果可能是正确的,但不适用于最新的 webdriver。这是我对上述问题的解决方案。简单又甜美
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()
或者
http_proxy = "http://ip:port"
https_proxy = "https://ip:port"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
}
driver = webdriver.Firefox(proxy=proxyDict)
尝试设置 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")
该程序在 Windows 8 和 Mac OSX 上测试。如果您使用的是 Mac OSX 并且没有更新 selenium,那么您可能会遇到 selenium.common.exceptions.WebDriverException
。如果是这样,请在升级硒后重试
pip install -U selenium
上面和 this question 上的答案要么不适用于 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(未代理)和外部(代理)。类似的代理设置也适用于手动配置。可以在代码 here 中看到可能的代理设置。
请注意,直接将代理对象作为 proxy=proxy
传递给驱动程序不起作用——它被接受但被忽略(应该有一个弃用警告,但在我的情况下,我认为 Behave 正在吞下它)。
正如@Dugini 所述,一些 config entries 已被删除。最大:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
这对我有用并允许使用无头浏览器,您只需要调用传递代理的方法。
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)
使用抓取 API 时,从任何在线资源抓取数据都非常容易。您可以尝试使用 scraper API 从网页中抓取信息,它会自动解析 Web 数据。 API 也可以集成到您的源代码中。除了使用 API 来抓取数据之外,您还可以尝试下面提到的美丽汤中的源代码来使用 CSS 选择器来抓取数据。在尝试此代码之前,请注意 select() 方法可用于查找大量元素。除此之外, 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/")
尝试运行 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()
prox.socks_version = 5
或prox.socks_version = 4
。那应该可以清除错误。