通过 Selenium 中的 webdriver 传递用户代理 [英] Pass the user-agent through webdriver in Selenium

查看:22
本文介绍了通过 Selenium 中的 webdriver 传递用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 中的 Selenium 进行网站抓取项目.当我通过浏览器打开主页时,它可以正常打开.

I am working on a website scraping project using Selenium in Python. When I open the homepage through a browser, it opens properly.

但是,当我尝试通过 Selenium 中的 webdriver() 打开网页时,它打开了一个完全不同的页面.

But, when I try to open the webpage through webdriver() in Selenium, it opens a completely different page.

我认为,它能够检测到user-agent(不确定它叫什么)并且能够检查浏览器的属性或其他东西.

I think, it is able to detect the user-agent( not sure what it is called) and is able to check the properties of the browser or something.

是否可以通过 webdriver() 传递属性以便加载正确的主页.

Is it possible to pass the properties though the webdriver() so that the right homepage is loaded.

谢谢

推荐答案

在 python 版本的 webdriver 中更改用户代理是通过更改浏览器的配置文件来完成的.我只通过传递配置文件参数为 webdriver.Firefox() 完成了此操作.您需要执行以下操作:

Changing the user agent in the python version of webdriver is done by altering your browser's profile. I have only done this for webdriver.Firefox() by passing a profile parameter. You need to do the following:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override","your_user_agent_string")
driver=webdriver.Firefox(profile)

每次您希望更改用户代理时,您都需要重新启动网络浏览器(即再次调用 driver=webdriver.Firefox(profile))

Every time you wish to change the user agent you will need to restart your web browser (i.e. call driver=webdriver.Firefox(profile) again)

如果您不确定您的用户代理字符串是什么,请在正确显示页面的浏览器上搜索我的用户代理是什么",然后复制并粘贴该字符串.

If you are unsure to what your user agent string is do a search for "what is my user agent" on a browser that displays the page properly and just copy and paste that one.

希望能解决这个问题.

这篇关于通过 Selenium 中的 webdriver 传递用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆