2017-03-05 43 views
1

使用Python 2.7和硒webdriver的,我想测试一个网站是否是移动友好的或不执行以下操作:如何用selenium和python获取网站的身宽?

  1. 打开一个网站,在“移动模式” - 启用(使用mobile_emulation)Chrome浏览器

  2. 获取网站

  3. body宽度的网站是大,可以说900px的body宽度(像素),比大多数手机的宽度,400像素例如,后来我才知道那个网站不友好。

我的代码:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 

mobile_emulation = { 
    "deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0}, 
    "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"} 

chrome_options = Options() 
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation) 
driver = webdriver.Chrome(executable_path=r'C:\Users\Jacob\PycharmProjects\Testing\chromedriver_win32\chromedriver.exe') 

driver.get('https://www.tripadvisor.nl/') 

body_width = driver.execute_script("return document.body.offsetWidth;") 

print(body_width) 

结果:

912 

Process finished with exit code 0 

问题:正确body宽度的website的移动版本是在这种情况下为360px和不912px(使用Chrome的“设备工具栏”在开发工具中进行检查)。所以我的脚本没有正常工作。我也有这个问题与其他网址。我该如何解决这个问题?

回答

1

你不通过chrome_options到驱动程序,请参阅以下内容:

driver = webdriver.Chrome(executable_path=r'C:\Users\Jacob\PycharmProjects\Testing\chromedriver_win32\chromedriver.exe', crome_options=chrome_options)

>>> driver = webdriver.Chrome(chrome_options=chrome_options) 
>>> driver.get('https://www.tripadvisor.nl/') 
>>> driver.execute_script("return document.body.offsetWidth;") 
360 
+0

太感谢你了!这帮了我很多! – jakeT888

相关问题