使用Python中的Javascript生成页面

xra*_*alf 26 html javascript python download urllib2

我想下载生成的网页Javascript,并将其存储在Python代码中的字符串变量中.单击按钮时会生成页面.

如果我知道我会使用的结果URL,urllib2但事实并非如此.

谢谢

jfs*_*jfs 37

你可以使用Selenium Webdriver:

#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
     browser.get(url)
     button = browser.find_element_by_name('button')
     button.click()
     # wait for the page to load
     WebDriverWait(browser, timeout=10).until(
         lambda x: x.find_element_by_id('someId_that_must_be_on_new_page'))
     # store it to string variable
     page_source = browser.page_source
print(page_source)
Run Code Online (Sandbox Code Playgroud)

  • 需要`someId_that_must_be_on_new_page`的`WebDriverWait`是什么?它只能用一些`sleep`或`delay`功能来完成吗?是否可以设置用户代理字符串? (3认同)