如何返回selenium browser(或如何导入返回selenium browser的def)

2024-04-24 22:54:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用函数中的特定设置(privoxy、Tor、randon user agent…)启动selenium浏览器,然后在代码中调用这个函数。我创建了一个python脚本mybrowser.py,其中包含以下内容:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from fake_useragent import UserAgent
from stem import Signal
from stem.control import Controller

class MyBrowserClass:
    def start_browser():
        service_args = [
            '--proxy=127.0.0.1:8118',
            '--proxy-type= http',
            ]
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)

        browser = webdriver.PhantomJS(service_args = service_args,         desired_capabilities=dcap)
        return browser

    def set_new_ip():
        with Controller.from_port(port=9051) as controller:
            controller.authenticate(password=password) 
            controller.signal(Signal.NEWNYM)

然后我将其导入另一个脚本myscraping.py,其中包含以下内容:

^{pr2}$

浏览器正在工作-我可以访问页面并使用.page_source检索它。在

但是第一次打印和第二次打印之间IP没有变化。如果我将函数的内容移到myscraping.py内(并删除import+函数调用),那么IP将发生变化。在

为什么?退回浏览器有问题吗?我该怎么解决这个问题?在


实际上,情况有点复杂。当我在调用mybrowser.set_new_ip()wait of 12 sec前后连接到https://check.torproject.org时,网页给出的IP在第一次和第二次调用之间发生变化。所以我的Ip被更改了(根据Tor),但是https://httpbin.org/ip和{}都没有检测到Ip的变化。在

...
browser.get("https://canihazip.com/s")
print(browser.page_source)
browser.get("https://check.torproject.org/")
print(browser.find_element_by_xpath('//div[@class="content"]').text )
mybrowser.set_new_ip()
time.sleep(12) 
browser.get("https://check.torproject.org/")
print(browser.find_element_by_xpath('//div[@class="content"]').text )
browser.get("https://canihazip.com/s")
print(browser.page_source)

所以打印出来的IP是这样的:

42.38.215.198 (canihazip before mybrowser.set_new_ip() )
42.38.215.198  (check.torproject before mybrowser.set_new_ip() )
106.184.130.30  (check.torproject after mybrowser.set_new_ip() )
42.38.215.198 (canihazip after  mybrowser.set_new_ip())

Privoxy配置:在C:\Program Files (x86)\Privoxy\config.txt中,我取消了这一行的注释(9050是Tor使用的端口):

forward-socks5t   /               127.0.0.1:9050 

Tor配置:在torcc中,我有这样一个:

ControlPort 9051
HashedControlPassword : xxxx

Tags: fromhttpsorgimportipbrowsernewget
2条回答

您可能需要检查是否有新的nym可用。在

is_newnym_available-如果tor当前接受NEWNYM信号,则为true

if controller.is_newnym_available(): controller.signal(Signal.NEWNYM)

这可能是因为内存的strong。因此,您第一次使用PhantomJS浏览器访问时可以得到一个动态结果,但该结果随后会被缓存,并且每次连续访问都会使用该缓存页面。在

这个内存缓存导致了如下问题:CSRF-Token在刷新时没有改变,现在我相信这是问题的根本原因。issue在2013年被提出并解决,但解决方案是一个方法,clearMemoryCache,可以在PhantomJS的WebPage类中找到。不幸的是,我们正在处理一个Seleniumwebdriver.PhantomJS实例。在

所以,除非我在监督一些事情,否则很难通过Selenium的抽象来访问这个方法。在

我认为唯一合适的解决方案是使用另一个不像PhantomJS那样具有内存缓存的webdriver。我用Chrome对它进行了测试,它的工作非常完美:

103.***.**.***
72.***.***.***

另外,作为补充说明,Selenium正在逐步淘汰PhantomJS:

UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead

相关问题 更多 >