LoginSignup
0
0

More than 1 year has passed since last update.

Selenium + ModHeader で Request Header を変えてみた

Last updated at Posted at 2022-06-25

はじめに

Selenium と Chrome拡張ツールの ModHeader を使ってRequestHeaderの「User-Agent Client Hints」を書き換えてページアクセスする方法。

今回はモバイル判定で利用する「sec-ch-ua-mobile」を「?1」に書き換えます。

環境

Java8
Selenium 4
WebDriverManager

準備

事前に「chrome-modheader」をダウンロードしておきます。

コード

Example.java
package example;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Example {
    private WebDriver driver;
    private StringBuffer verificationErrors = new StringBuffer();
    @BeforeClass
    public static void setupClass() {
        WebDriverManager.chromedriver().setup();
    }
    @Before
    /**
     * https://stackoverflow.com/questions/71668952/how-to-set-user-agent-client-hint-sec-ch-ua-in-selenium-python
     * */
    public void setUp() throws Exception {
        //ダウンロードしたModHeaderのパスを指定
        Path currentRelativePath = Paths.get("chrome-modheader/modheader.crx");
        ChromeOptions options = new ChromeOptions();
        options.addExtensions(new File(currentRelativePath.toAbsolutePath().toString()));

        driver = new ChromeDriver(options);
        
        //headerを付与
        String secUaMobile = "?1";
        driver.get("https://webdriver.modheader.com/add?sec-ch-ua-mobile=" + secUaMobile);
    }
    @Test
    public void ModHeaderを使うテスト() throws Exception {
        driver.get("https://www.yahoo.co.jp/");

    }
    @After
    public void tearDown() throws Exception {
        driver.quit();
    }
}

最後に

Selenium では Request Header をいじることができないとのことなので、自分自身の備忘録のためこの記事を書きました。
Chrome 113 から「User Agent(UA)」の情報が削減されることが決まりました。
Seleniumでスマートフォン向けサイトのテストをする場合、スマートフォン用のUAを使ってアクセスしていましたが、
UAが削減されると、各WebページはUAの代わりに「User-Agent Client Hints」を使ってデバイスを判定することになりそうです。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0