我的程序接受用户输入并通过特定网页进行搜索。此外,我希望它可以点击特定链接,然后下载那里的文件。
示例:
- 网页:http://www.rcsb.org/pdb/home/home.do
- 搜索词:“1AW0”
- 在网站上搜索该词后,您将进入: http://www.rcsb.org/pdb/explore/explore.do?structureId=1AW0
我希望程序位于网页右侧并从下载文件选项下载 pdb 文件
我已经成功地使用 mechanize 模块编写了一个程序来自动搜索单词,但是无法找到点击链接的方法
我的代码:
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 模块来尝试完成这项工作。
提前致谢
最佳答案
我会这样做:
'''
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')
它提供了这个输出:
Saved to 1AW0.pdb
Saved to 1AW0.xml
Invalid filetype... png
连同 2 个文件 1AW0.pdb
和 1AW0.xml
一起保存到脚本目录(对于本例)。
http://docs.python.org/2/library/urllib.html#urllib.urlretrieve
关于python - 我如何编写一个程序来单击Python中的特定链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784390/