【问题标题】:Python + Selenium + PhantomJS render to PDF - multiple filesPython + Selenium + PhantomJS 渲染为 PDF - 多个文件
【发布时间】:2015-07-01 18:55:37
【问题描述】:

我正在尝试添加在

中找到的代码

Python + Selenium + PhantomJS render to PDF

所以我不是将一个网页保存为 pdf 文件,而是可以遍历一个 url 列表并使用特定名称(来自另一个列表)保存每个。

count = 0
while count < length:
    def execute(script, args):
        driver.execute('executePhantomScript', {'script': script, 'args' : args })

    driver = webdriver.PhantomJS('phantomjs')

    # hack while the python interface lags
    driver.command_executor._commands['executePhantomScript'] = ('POST',     '/session/$sessionId/phantom/execute')

    driver.get(urls[count])

    # set page format
    # inside the execution script, webpage is "this"
    pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
    execute(pageFormat, [])

    # render current page
    render = '''this.render("test.pdf")'''
    execute(render, [])

    count+=1

我测试了修改

render = '''this.render("test.pdf")'''

render = '''this.render(names[count]+".pdf")'''

以便使用count将每个名称包含在列表中但没有成功。

也试过了:

dest = file_user[count]+".pdf"

render = '''this.render(dest)'''
execute(render, [])

但也没有用。

非常感谢有关适当语法的建议。

一定很简单,但我是个菜鸟。

【问题讨论】:

  • Python 不是 php,您可以简单地在字符串中使用变量。您必须将字符串连接在一起或使用格式化程序。
  • 感谢@ArtjomB 的评论

标签: html python-2.7 pdf selenium-webdriver phantomjs


【解决方案1】:

使用string formatting:

render = 'this.render("{file_name}.pdf")'.format(file_name=names[count])

【讨论】:

  • 太棒了!它工作得很好。太感谢了!!该链接是一个很棒的奖励。
  • 一个附加问题...使用beautifulsoup我提取了html的一些部分并替换了标签中的一些文本,问题是它仍然从初始链接呈现原始html...你怎么办建议?我应该把它作为一个不同的问题发布吗?谢谢!
  • @Diego 是的,单独解决是有意义的
猜你喜欢
  • 2023-04-03
  • 2018-02-16
  • 2016-11-21
  • 2014-01-31
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多