javascript - 使用 Python 从网站下载 Javascript 文件

标签 javascript python download bioinformatics

我正在尝试使用 python 从以下网站下载结果:

http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY

在我意识到下载文件是用 mechanize 不支持的 javascript 编写的之前,我曾尝试使用 mechanize。到目前为止,我的代码打开网页如下所示。我被困在如何访问网页上的下载链接以将数据保存到我的机器上。

import urllib2

def downloadFile():

    url = 'http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY'
    t = urllib2.urlopen(url)
    s = t.read()
    print s

打印出来的结果是

<html>
<head></head>
<body>
  <form name="apiForm" method="POST">
    <input type="hidden" name="rowids">
    <input type="hidden" name="annot">

    <script type="text/javascript">
      document.apiForm.rowids.value="4791928,3403495,....";   //There are really about 500 values
      document.apiForm.annot.value="48";
      document.apiForm.action = "chartReport.jsp";
      document.apiForm.submit();
    </script>

  </form>
</body>
</html>

有人知道如何选择并转到“下载文件”页面并将该文件保存到我的计算机吗?

最佳答案

在对该链接进行更多研究后,我想到了这个。您绝对可以使用机械化来做到这一点。

import mechanize

def getJSVariableValue(content, variable):
    value_start_index = content.find(variable)
    value_start_index = content.find('"', value_start_index) + 1

    value_end_index = content.find('"', value_start_index)

    value = content[value_start_index:value_end_index]
    return value

def getChartReport(url):
    br = mechanize.Browser()
    resp = br.open(url)
    content = resp.read()
    br.select_form(name = 'apiForm')
    br.form.set_all_readonly(False)
    br.form['rowids'] = getJSVariableValue(content, 'document.apiForm.rowids.value')
    br.form['annot'] = getJSVariableValue(content, 'document.apiForm.annot.value')
    br.form.action = 'http://david.abcc.ncifcrf.gov/' + getJSVariableValue(content, 'document.apiForm.action')

    print br.form['rowids']
    print br.form['annot']

    br.submit()

    resp = br.follow_link(text_regex=r'Download File')
    content = resp.read()
    f = open('output.txt', 'w')
    f.write(content)


url = 'http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY'
chart_output = getChartReport(url)

关于javascript - 使用 Python 从网站下载 Javascript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444824/

相关文章:

python - 使用 urllib2 加速多次下载

javascript - Firestore 一个范围查询,在不同的字段上排序

仅当不是未定义/空/空时,Javascript 才将 .join() 应用于对象集合中的项目?

包含数据文件的 Python 包

android - 如何使用PRDownloader库下载文件

javascript - React-Native:下载图像并将其转换为 Base64 图像

javascript - 在数组中创建对象的副本

javascript - 从 HTML 导入文件保存到 localStorage

Python:如何并行运行两个函数

python - 如何使用 Numpy 对字符串数组进行一次性编码?