python - 点击后类似的截图

标签 python html selenium web-scraping phantomjs

我正在尝试截取 this page 的屏幕截图使用 Selenium 。但由于 Chrome 和 Firefox 不允许全屏截图,所以我使用 PhantomJS。

有 2 组持续时间:12 个月逐月。因此,我尝试单击每个选项卡并截取屏幕截图。

获取页面内容的代码为:

browser = webdriver.PhantomJS()
browser.set_window_size(1366, 728)
browser.get("http://www.optus.com.au/shop/broadband/mobile-broadband/data-sim-card")
delay = 30 # seconds
try:
    wait = WebDriverWait(browser, delay)
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.price")))
    print("\nPage is ready!")
except TimeoutException:
    print("Loading took too much time!")

html = browser.page_source
soup = BeautifulSoup(html, "html.parser")

获取持续时间的 CSS 类名:

durations = soup.body.find("ul", attrs={'class': 'filter-options grouped'})
duration_filtrs = {}
for content in durations.contents:
    duration = content.text  # Storage of the model 64GB, 256GB, 512GB
    css_clss = list(filter(lambda x: x not in ['', 'active'], content.attrs['class']))
    filtr_nm = '.' + '.'.join(css_clss)
    duration_filtrs[duration] = filtr_nm

print(duration_filtrs) 
# {'12 Months': '.filter-option.contract_length_12', 'Month to Month':'.filter-option.contract_length_1'}

要截取每个持续时间选项卡的屏幕截图,

for duration, css_cls in duration_filtrs.items():
    browser.find_element_by_css_selector(css_cls).click()
    browser.save_screenshot(duration+'.png')

使用上面的代码,即使文件大小略有不同,我也会得到相似的屏幕截图。

有人可以告诉我我做错了什么吗?

最佳答案

我不知道如何解决 PhantomJS 中的这个问题。我推荐使用 Chrome headless 的解决方法,如下所示。您只需要指定窗口大小。

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=2160,3840") # you can adjust the size as you want
browser = webdriver.Chrome(chrome_options=chrome_options)
...
...
for duration, css_cls in duration_filtrs.items():
    button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,css_cls)))
    browser.save_screenshot('before-'+duration+'.png')
    print(button.text)
    button.click()
    time.sleep(8)
    browser.save_screenshot(duration+'.png')

关于python - 点击后类似的截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555250/

相关文章:

python - 如何在 Python 中获取实例变量?

html - 在html中保留原始图像的高度和大小

php - Laravel 限制字符 - PHP

python - Selenium:页面显示不同

Selenium 中的java反射

c# - 使用 html agility xpath 查找 webdriver 元素

python - 将函数值插入 SQLite 数据库

python - jinja2 模板的多个渲染?

PHP 相当于 Python 的 repr()

css - Bootstrap Inline-Horizo​​ntal Form 设计