Python method to get the image download address on a web page

  • 2020-04-02 14:40:08
  • OfStack

This article demonstrates an example of how Python can get an image download address on a web page. Share with you for your reference. The details are as follows:

Here to get the download address of the picture on the web page is a section of the data collection being written, the code is as follows:

#!/user/bin/python3
import urllib2
from HTMLParser import HTMLParser
class MyHtmlParser(HTMLParser):
    links = []
    def handle_starttag(self, tag, attrs):
        if tag == "img":
            if len(attrs) == 0:
                pass
            else:
                for name, value in attrs:
                    if name == "src":
                        self.links.append(value)
if __name__ == "__main__":
    uri = "http://dy.163.com/v2/article/T1374483113516/AGSNE9L000964K4O"
    file = urllib2.urlopen(uri).read()
    # file = "<html><h1>Title</h1><p>I'm a paragraph!</p></html>"
    hy = MyHtmlParser()
    hy.feed(file)
    hy.close()
    print(hy.links)

I hope this article has helped you with your Python programming.


Related articles: