在Python中,如何编写一个单击特定链接的程序

2024-05-16 19:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序接受用户输入并在特定网页中搜索。此外,我想让它去点击一个特定的链接,然后下载那里的文件。在

示例:

  1. 网页:http://www.rcsb.org/pdb/home/home.do
  2. 搜索词:“1AW0”
  3. 在网站上搜索该词后,您可以: http://www.rcsb.org/pdb/explore/explore.do?structureId=1AW0

我希望程序转到网页的右侧,从下载文件选项下载pdb文件

我已经设法写了一个程序使用机械化模块,以自动搜索词,但找不到一个方法,我可以点击一个链接

我的代码:

import urllib2
import re
import mechanize

br = mechanize.Browser()
br.open("http://www.rcsb.org/pdb/home/home.do")
## name of the form that holds the search text area 
br.select_form("headerQueryForm")

## "q" name of the teaxtarea in the html script
br["q"] = str("1AW0")
response = br.submit()
print response.read() 

任何帮助或建议都会有帮助。在

顺便说一句,我是Python的中级程序员,我正试图学习Jython模块来实现这一点。在

提前谢谢


Tags: 文件theorgbrimport程序http网页
1条回答
网友
1楼 · 发布于 2024-05-16 19:56:00

我会这样做的:

'''
Created on Dec 9, 2012

@author: Daniel Ng
'''

import urllib

def fetch_structure(structureid, filetype='pdb'):
  download_url = 'http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=%s&compression=NO&structureId=%s'
  filetypes = ['pdb','cif','xml']
  if (filetype not in filetypes):
    print "Invalid filetype...", filetype
  else:
    try:
      urllib.urlretrieve(download_url % (filetype,structureid), '%s.%s' % (structureid,filetype))
    except Exception, e:
      print "Download failed...", e
    else:
      print "Saved to", '%s.%s' % (structureid,filetype)

if __name__ == "__main__":
  fetch_structure('1AW0')
  fetch_structure('1AW0', filetype='xml')
  fetch_structure('1AW0', filetype='png')

它提供以下输出:

^{pr2}$

以及保存到脚本目录中的两个文件1AW0.pdb1AW0.xml(在本例中)。在

http://docs.python.org/2/library/urllib.html#urllib.urlretrieve

相关问题 更多 >