【问题标题】:Rotating IP with selenium and Tor使用 selenium 和 Tor 旋转 IP
【发布时间】:2019-07-02 11:58:01
【问题描述】:

我有一个用于抓取特定 HTTP 请求的 selenium 配置,该请求仅在我单击网站的特定 REACT 元素时发送。 这就是我使用硒的原因......找不到其他方法。

每次我想抓取这个特定的 HTTP 请求时,我都必须更新我的 IP。 为此,我使用 Tor。 当我启动我的 python 脚本时,它运行良好,Tor 设置了一个新的 ip 并抓取了我想要的内容。 我在脚本中添加了 try/catch,如果我的脚本第一次无法运行,它将重试 10 次。

问题是当我的脚本再次尝试时,IP 不能再旋转了......

如何做到这一点?



import time
from random import randint
from time import sleep
import os
import subprocess
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from seleniumwire import webdriver
from selenium.webdriver.firefox.options import Options
from fake_useragent import UserAgent



options_wire = {
    'proxy': {
        'http': 'http://localhost:8088',
        'https': 'https://localhost:8088',
        'no_proxy': ''
    }
}

def firefox_init():
    os.system("killall tor")
    time.sleep(1)
    ua = UserAgent()
    user_agent = ua.random
    subprocess.Popen(("tor --HTTPTunnelPort 8088"),shell=True)
    time.sleep(2)
    return user_agent


def profile_firefox():
    profile = FirefoxProfile()
    profile.set_preference('permissions.default.image', 2)
    profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
    profile.set_preference("general.useragent.override", firefox_init())
    profile.set_preference("driver.privatebrowsing.autostart", True)
    profile.update_preferences()
    return profile



def options_firefox():
    options = Options()
    options.headless = False
    return options


def firefox_closing(driver):
    driver.quit()
    time.sleep(3)
    os.system('killall tor')
      


def headless(url):
    for x in range(0, 10):
        profile = profile_firefox()
        options = options_firefox()
        driver = webdriver.Firefox(seleniumwire_options=options_wire,firefox_profile=profile, options=options, executable_path='******/headless_browser/geckodriver')
        driver.set_window_position(0, 0)
        driver.set_window_size(randint(1024, 2060), randint(1024, 4100))
        # time.sleep(randint(3,10))
        driver.get(url)
        time.sleep(randint(3,8))
        try:
            if driver.find_element_by_xpath("//*[@id=\"*******\"]/main/div/div/div[1]/div[2]/form/div/div[2]/div[1]/button"):
                # driver.find_element_by_xpath("//*[@id=\"*******\"]/main/div/div/div[1]/div[2]/form/div/div[2]/div[1]/button").click()
                # time.sleep(randint(8,10))
                driver.find_element_by_xpath("//*[@id=\"*******\"]/main/div/div/div[1]/div[2]/form/div/div[2]/div[1]/button").click()
                time.sleep(randint(3,6))
                for request in driver.requests:
                    if request.path == "https://api.*********.***/*******/*********":
                        request_api = request
                        raw = str(request_api.body)
                        request_api = raw.split(('b\''))
                        payload_raw = request_api[1]
                        payload = payload_raw[:-1]
                        if payload:
                            header = request.headers
                            print(header, payload)
                            break
                else:
                    continue
                break
    
        except:
            firefox_closing(driver)
            time.sleep(5)
        finally:
            firefox_closing(driver)

            
    return header, payload


url="https://check.torproject.org/?lang=fr"
headless(url)

谢谢

【问题讨论】:

    标签: python selenium tor


    【解决方案1】:

    好吧,我不可能知道自从你杀死了 tor 进程后它是如何不更新 IP 地址的。即使您将 tor 作为服务放入 Systemd 中,它也会在您重新启动服务时更新,当然。但我可能会给你一些指示:

    • 在假代理模块上,尝试禁用缓存以避免缓存在 /tmp 目录中或使用托管缓存服务器:
    
        ua = UserAgent(cache=False, use_cache_server=False)
    
    
    • 将 Tor 放在 systemd 上并避免使用 os.system(),它不安全,而且当您直接在脚本上输入系统命令时,它会出现很多缺陷。使用服务文件,您可能只需重新启动服务即可更新您的 IP 地址。您可能希望使用 Arch Linux Wiki 参考在 here 中配置您自己的 TOR 环境!

    【讨论】:

    • 感谢卡洛斯的回答。在我的多次测试中,我认为问题出在 seleniumwire 包本身。当我导入官方 selenium webdriver 时,Tor 可以每次更新 IP,selenium 每次都使用新 IP。如果 webdriver 被杀死时连接关闭,我正在查看包。
    【解决方案2】:

    为了实现这一点,我使用了其他代理,selenium-wire 非常好,但需要修复。

    我使用了 Browsermob 代理并设置了一个上游代理来使用。 结果是您可以捕获每个 HTTP 请求或响应解析它,并且每次旋转 ip 并使用 tor HTTPTunnelPort 配置。

        proxy_params = {'httpProxy': 'localhost:8088', 'httpsProxy': 'localhost:8088'}
        proxy_b = server.create_proxy(params=proxy_params)
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多