-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathlinks.py
More file actions
70 lines (53 loc) · 2.1 KB
/
links.py
File metadata and controls
70 lines (53 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import requests
from bs4 import BeautifulSoup
def getOutBoundURLs(anchors):
'''http://www.w3.org/TR/html5/text-level-semantics.html#the-a-element
anchors contains all \<a\> tag elements from the HTML content.
Iterate through the list of anchors and build list containing
the href addresses whenever it is available.
@author kgashok
'''
addressList = []
for anchor in anchors:
try:
linkaddress = anchor.attrs['href']
addressList.append(linkaddress)
except BaseException:
print("Ignoring", anchor)
return addressList
def getOutBoundHttpURLs(alist):
return [address for address in alist if address.startswith("https:")]
def generateBanner(url, anchorCount, outBoundCount, linkCount):
return '''
#############################
---- Outbound links for {0} ({1}, {2}, https: {3})
#############################
'''.format(url, str(anchorCount), str(outBoundCount), str(linkCount))
def printURLs(url, anchors, f=None):
'''
Print only those addresses that start with 'https' from valid anchors
if 'f'ilename is valid, write extracted URLs to file as well
'''
outBoundURLs = getOutBoundURLs(anchors)
hhrefs = getOutBoundHttpURLs(outBoundURLs)
banner = generateBanner(url, len(anchors), len(outBoundURLs), len(hhrefs))
print(banner)
if f:
f.write(banner)
for linkaddress in hhrefs:
print(linkaddress)
if f:
f.write(url + " -> " + linkaddress + "\n")
urls = ["http://www.python.org", "http://www.facebook.com", "http://www.kct.ac.in", "http://www.psgtech.edu", "http://www.kgkite.ac.in" # , "http://www.kghospital.com"
# , "http://www.kgisl.com"
, "http://www.sece.ac.in", "http://www.siet.ac.in", "http://www.bennett.edu.in"
]
dataFile = open("data.txt", "w")
for url in urls:
html = requests.get(url)
soup = BeautifulSoup(html.text)
anchors = soup.find_all("a")
# equivalent one-liner
# anchors = BeautifulSoup(requests.get("http://www.python.org").text).find_all('a')
printURLs(url, anchors, dataFile)
dataFile.close()