【问题标题】:How Can I Get The Web-Loaded HTML of The Current Page in Selenium?如何在 Selenium 中获取当前页面的 Web 加载 HTML?
【发布时间】:2022-01-10 08:27:48
【问题描述】:

我有一个页面,我必须登录才能获取我想使用 BeautifulSoup 抓取的页面。我的代码目前看起来像

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Firefox();
//loginpage is the page where I have to login. It is just used as a placeholder for this question
driver.get("loginpage");
driver.find_element_by_id("username").send_keys("username");
driver.find_element_by_id("password").send_keys("password");
driver.find_element_by_xpath("//button[@onclick=\"return validateFields();\"]").click();
//contentpage is where I get the content to scrape from. It is also just used as a placeholder for this question.
driver.get("contentpage");
html = driver.page_source;
soup = BeautifulSoup(html, features="lxml");
status = soup.find_all("span");
for status in status:
    print(status);

但我认为 HTML 是错误的页面,因为当我可以查看浏览器并看到它应该存在时,BeautifulSoup 正在返回 NoneType。

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping beautifulsoup


    【解决方案1】:

    一旦您调用 get() 并且在提取 page_source 之前,您需要为任何 可见 元素,您可以使用以下Locator Strategy

    driver.get("contentpage")
    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "css_of_a-visible_element")))
    html = driver.page_source
    

    作为替代方案,您也可以使用 document.documentElement.outerHTML,如下所示:

    driver.get("contentpage")
    WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "css_of_a-visible_element")))
    html = driver.execute_script("return document.documentElement.outerHTML")
    

    参考文献

    您可以在以下位置找到一些相关的详细讨论:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多