我正在尝试抓取网站“http://everydayhealth.com”。但是,我发现页面会动态呈现。所以,当我点击“更多”按钮时,会显示一些新消息。但是,使用 splinter 来点击按钮不会让“browser.html”自动改变为当前的 html 内容。有没有办法让它使用 splinter 或 selenium 获取最新的 html 源代码?我在splinter中的代码如下:
import requests
from bs4 import BeautifulSoup
from splinter import Browser
browser = Browser()
browser.visit('http://everydayhealth.com')
browser.click_link_by_text("More")
print(browser.html)
根据@Louis的回答,我重写了程序如下:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Firefox()
driver.get("http://www.everydayhealth.com")
more_xpath = '//a[@class="btn-more"]'
more_btn = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(more_xpath))
more_btn.click()
more_news_xpath = '(//a[@href="http://www.everydayhealth.com/recipe-rehab/5-herbs-and-spices-to-intensify-flavor.aspx"])[2]'
WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath(more_news_xpath))
print(driver.execute_script("return document.documentElement.outerHTML;"))
driver.quit()
但是,在输出的文本中,我仍然找不到更新页面中的文本。例如,当我搜索“Is Milk Your Friend or Foe?”时,它仍然没有返回任何结果。有什么问题?
最佳答案
使用 Selenium,假设 driver
是您初始化的 WebDriver
对象,这将为您提供与调用时 DOM 状态对应的 HTML :
driver.execute_script("return document.documentElement.outerHTML;")
返回值是一个字符串,所以你可以这样做:
print(driver.execute_script("return document.documentElement.outerHTML;"))
关于python - 碎片或 Selenium : Can we get current html page after clicking a button?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809954/