-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
78 lines (63 loc) · 2.44 KB
/
Copy pathtest.py
File metadata and controls
78 lines (63 loc) · 2.44 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
71
72
73
74
75
76
77
78
# Import required packages
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import time
from bs4 import BeautifulSoup
# # Define the chromedriver service
# s = Service('chromedriver.exe')
# # Instantiate the webdriver
# driver = webdriver.Chrome(service=s)
# Path to the chromedriver executable
chromedriver_path = '/path/to/chromedriver'
# Define the chromedriver service
s = Service(chromedriver_path)
# Set the path to the Chrome binary (optional)
# If you have Chrome installed in the default location, you can skip this step
# Create a new ChromeDriver instance
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
# The base URL for the pages to scrape
page_URL = "https://leetcode.com/problemset/all/?page="
# Function to get all the 'a' tags from a given URL
def get_a_tags(url):
# Load the URL in the browser
driver.get(url)
# Wait for 7 seconds to ensure the page is fully loaded
time.sleep(7)
# Find all the 'a' elements on the page
links = driver.find_elements(By.TAG_NAME, "a")
ans = []
# Iterate over each 'a' element
for i in links:
try:
# Check if '/problems/' is in the href of the 'a' element
if "/problems/" in i.get_attribute("href"):
# If it is, append it to the list of links
ans.append(i.get_attribute("href"))
except:
pass
# Remove duplicate links using set
ans = list(set(ans))
return ans
# List to store the final list of links
my_ans = []
# Loop through the pages you're interested in (in this case, pages 1-54)
for i in range(1, 55):
# Call the function to get the 'a' tags from each page and append the results to your list
my_ans += (get_a_tags(page_URL+str(i)))
# Remove any duplicates that might have been introduced in the process
my_ans = list(set(my_ans))
# Open a file to write the results to
with open('lc.txt', 'a') as f:
# Iterate over each link in your final list
for j in my_ans:
# Write each link to the file, followed by a newline
f.write(j+'\n')
# Print the total number of unique links found
print(len(my_ans))
# Close the browser
driver.quit()