Download the Python script for the physics article

Source: Internet
Author: User

Although I am a physical slag, nothing or like to see the physical aspects of the content to edify sentiment. A good source is "physics", where the article is free to download. But a download a little trouble, and save the filename is the article title of the Utf-8 code, the end will have to change the file name. The article is not directly written in the Web page, but in the click to download the time generated, so like DownThemAll, thunder and other tools are useless. Then you write a download script.

By looking at the source of the Web page, it is generated by the type of file (which should be pdf) and the ID. It is using the post, I use GET, I am not very clear about the difference between this, also ready to learn the content of jquery.

I originally wanted to be able to download only articles of interest. Each article on the page should have a tick box, the corresponding article will be highlighted after the check, to tell the truth I do not know what the site to do with this. Maybe I can tick the article of interest and then download it. When checked, this element's class will change from Noselectrow to Selectedrow. The relevant code is as follows:

function hightlightrowaction (rowid) {    var thisrow = $ ("#" +rowid);     if ($ (Thisrow). Hasclass ("Selectedrow")) {        $ (thisrow). Removeclass ("Selectedrow");        $ (Thisrow). addclass ("Noselectrow");     Else {        $ (thisrow). addclass ("Selectedrow");        $ (Thisrow). Removeclass ("Noselectrow");}    }
View Code

But sometimes the class did not change after the check, it seems a bit of a problem, still do not understand.

The Python script follows, using BeautifulSoup and requests. The regular expression is very slag-written.

1 #-*-coding:utf-8-*-2 """3 This script was used to download file from physical (http://www.wuli.ac.cn/CN/volumn/home.shtml) automatically.4 Example Usage:5 6 downloadfiles (U ' f:\\ physics \ \ ', "http://www.wuli.ac.cn/CN/volumn/volumn_1696.shtml")7 """8 ImportRequests9  fromBs4ImportBeautifulSoupTen ImportUrllib One ImportRe A ImportOS - defHasdownloadlink (tag): -     returnTag.has_attr ('onclick') andtag['onclick'].startswith ('Showarticlefile') the  - defGetfiletypeandid (fileInfo): -     """ - :p Aram FileInfo: + : Return:file type (usually pdf) and file ID -     """ +m = Re.match (r'[ ^,]*,\s*[\ '] (. *) [\ ' \ '][^,]*,\s* ([^\)]*). *', FileInfo) A     returnM.groups () [0], m.groups () [1] at  - defGetpublicationyearmonth (tag): -     """ - :p Aram Tag: - : return:publication Year and Month in the form yyyy-mm -     """ in     returnRe.match (R'. * (\d{4}-\d{2}). *', Tag.get_text ()). groups () [0] -  to defModifyfilename (fname): +     #get rid of characters which is not allowed to is used in file name by Windows -      forInvalidcharinchR'\/:?" <>|': thefname = Fname.replace (Invalidchar,"') *     returnfname $ Panax Notoginseng defWritelog (Savedirectory, errmsg): -Fhandle = open (Savedirectory +"Download Log.txt",'W') the      forMsginchErrMsg: +Fhandle.write (Msg.encode ('Utf-8')); A fhandle.close () the  + defDownloadfiles (savedirectory, url, onlydownloadseleted =False): -     """ $ :p Aram Savedirectory:directory to store the downloaded files $ :p Aram Url:url of the download page - :p Aram Onlydownloadseleted:not implemented yet. Ideally, it should allow one to download only interested instead of all files. - : Return:none the     """ -page =urllib.urlopen (URL)WuyiSoup =BeautifulSoup (page) theVolumeanddatetag = Soup.find (class_="STYLE5") -Yearmonth =getpublicationyearmonth (Volumeanddatetag) WuYear = Yearmonth[:4] -RelativePath = year +"\\"+ Yearmonth +"\\" AboutAbsolutepath = Savedirectory +RelativePath $     if  notos.path.exists (absolutepath): - os.makedirs (Absolutepath) -Articlemark ="Selectedrow" ifonlydownloadseletedElse "Noselectrow" -Articles = Soup.find_all (Class_ =Articlemark) AErrMsg = [] +      forIndex, articleinchEnumerate (articles, 1): the         Print 'downloading the%d th file,%d left.'% (index, Len (articles)-index) -         #The title of one article in contained in the first anchor $title = Article.find ('a'). Get_text () thetitle =Modifyfilename (title) the         Try: theDownloadanchor =Article.find (Hasdownloadlink) theFileInfo = downloadanchor['onclick'] -FileType, FileID =Getfiletypeandid (fileInfo) inFileName = Title+'.'+Filetype.lower () theFilePath = Absolutepath +FileName theparam = {"Attachtype": FileType,"ID": FileID} About             if  notos.path.exists (filePath): theArticlefile = Requests.get ("http://www.wuli.ac.cn/CN/article/downloadArticleFile.do", params=param) theFhandle = open (FilePath,"WB") the fhandle.write (articlefile.content) + fhandle.close () -         except: theErrmsg.append (title +"Download Failed")Bayi  the     ifLen (errmsg) >0: the Writelog (Absolutepath, errmsg) -  - if __name__=="__main__": theDownloadfiles (U'f:\\ physics \ \',"http://www.wuli.ac.cn/CN/volumn/volumn_921.shtml")
View Code

Download the Python script for the physics article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.