Guest User

Untitled

a guest
Mar 29th, 2024
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. from bs4 import BeautifulSoup
  2. import requests
  3.  
  4. session = requests.Session()
  5. session.headers.update({
  6. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
  7. })
  8.  
  9. def parse_and_scrape(url, visitedLinks, filename="links.txt", max_links=100000, depth=0, max_depth=10):
  10. if depth > max_depth:
  11. return
  12.  
  13. try:
  14. # Check if the link has been visited
  15. if url in visitedLinks or url == '':
  16. return
  17.  
  18. resp = session.get(url)
  19. soup = BeautifulSoup(resp.content, "html.parser")
  20. links = []
  21. counter = 0
  22.  
  23. for link in soup.find_all('a'):
  24. href = link.get('href')
  25. if href and href.startswith("https://") and counter < max_links:
  26. links.append(href)
  27. print(href)
  28. counter += 1
  29.  
  30. # Write new links to the file and update visitedLinks set
  31. with open(filename, 'a') as file:
  32. for link in links:
  33. if link not in visitedLinks:
  34. file.write(link + '\n')
  35. visitedLinks.add(link)
  36. # Recursively scrape the new link
  37. print("next: " + link)
  38. parse_and_scrape(link, visitedLinks, filename, max_links, depth+1, max_depth)
  39. except requests.exceptions.RequestException as e:
  40. print("Failed to open: " + url + " | " + str(e))
  41.  
  42. # Initialize visited links set
  43. visitedLinks = set()
  44. # Read existing links from the file
  45. try:
  46. with open("links.txt", 'r') as file:
  47. visitedLinks.update(set(file.read().splitlines()))
  48. except FileNotFoundError:
  49. pass
  50.  
  51. # Example usage
  52. parse_and_scrape("https://cnn.com", visitedLinks)
Advertisement
Add Comment
Please, Sign In to add comment