Created
November 14, 2017 18:37
-
-
Save davidejones/96725c480bf9a17d497f9d07b6c96e4f to your computer and use it in GitHub Desktop.
Get all hrefs from a url with python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from html.parser import HTMLParser | |
import urllib.request | |
class LinkParser(HTMLParser): | |
def __init__(self, *, convert_charrefs=True): | |
super().__init__(convert_charrefs=convert_charrefs) | |
self.links = [] | |
def handle_starttag(self, tag, attrs): | |
if tag == 'a': | |
self.links.extend([v for k, v in attrs if k == 'href']) | |
def main(): | |
with urllib.request.urlopen('http://python.org') as r: | |
if r.code == 200: | |
html = r.read() | |
parser = LinkParser() | |
parser.feed(str(html)) | |
print(parser.links) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment