One, get the entire page data
urllib The module provides read web . First, we define a gethtml () :
Urllib.urlopen () method is used to open a url
The read () method is used to read the data on the URL , pass a URL to the gethtml () function , and download the entire page. The execution program will print out the entire page.
#coding =utf-8import urllibdef gethtml (URL): page = urllib.urlopen (URL) html = page.read () return htmlhtml = getht ML ("http://tieba.baidu.com/p/2460150866") Print HTML
Second, to filter the data you want in the page (here is an example of a picture, the previous article has introduced the filter post)
The core step is to use regular expressions to filter out the content of the specified format, which is what you want.
The RE module consists mainly of regular expressions:
Re.compile () can compile a regular expression into a regular expression object.
The Re.findall () method reads the data in the HTML that contains the Imgre (regular expression).
Image Area HTML code:
The run script will get the URL address of the entire page that contains the picture, and the return value is a list
Import reimport urllibdef gethtml (URL): page = urllib.urlopen (URL) html = page.read () return htmldef getimg (HTML) : Reg = R ' src= "(. +?\.jpg)" Pic_ext ' Imgre = Re.compile (reg) imglist = Re.findall (imgre,html) return imglist html = gethtml ("http://tieba.baidu.com/p/2460150866") print getimg (HTML)
Third, save the picture to a local
In contrast to the previous step, the core is to use the Urllib.urlretrieve () method to directly download remote data to the local.
through a loops through the captured picture connection, in order to make the picture's file name look more canonical, rename it, and the naming convention passes through x variable plus 1
#coding =utf-8import urllibimport redef gethtml (URL): page = urllib.urlopen (URL) html = page.read () return htmldef Getimg (HTML): Reg = R ' src= "(. +?\.jpg)" Pic_ext ' Imgre = Re.compile (reg) imglist = Re.findall (imgre,html) x = 0 for Imgurl in Imglist:urllib.urlretrieve (Imgurl, ' d:/%s.jpg '% x) x+=1html = gethtml ("Http://tieba.baid u.com/p/2460150866 ") getimg (HTML)
This article is from the "Seeworld" blog, make sure to keep this source http://depops2016.blog.51cto.com/4205997/1771517
"Python learning" web crawler--Basic Case Tutorial