【问题标题】:Similar looking screenshots after clicking点击后类似的截图
【发布时间】:2018-02-01 04:16:06
【问题描述】:

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

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

获取页面内容的代码为:

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')

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

谁能告诉我我做错了什么?

【问题讨论】:

  • 你的意思是说标签似乎没有被切换?
  • 当我使用 Chrome(而不是 PhantomJS)和屏幕截图(即使它们不是整页)对我来说看起来正确

标签: python html selenium web-scraping phantomjs


【解决方案1】:

我不知道如何在 PhantomJS 中解决这个问题。我建议使用 Chrome 无头的解决方法如下。您只需要指定窗口大小。

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')

【讨论】:

  • 感谢 Buaban 的脚本。为此+1。我从来没有新的如何运行Chrome headless 浏览器。按照您的指导,我取得了成功。虽然想知道一件事。 selenium headless browser 可以在需要的时候成功点击,不像PhantomJS
  • @SIM 当然。无头模式的工作原理与 GUI 模式相同。
  • 非常感谢您的尖锐回复。
  • 谢谢。我真的很想捕捉价格部分的截图。你能告诉我怎么做吗?
  • 这些对我有用。谢谢options = webdriver.ChromeOptions() options.add_argument('headless') options.add_argument("window-size=2160x3840") # you can adjust the size as you want browser = webdriver.Chrome(chrome_options=options)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多