-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsing_script.py
84 lines (66 loc) · 2.67 KB
/
parsing_script.py
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
79
80
81
82
83
import requests
from bs4 import BeautifulSoup
import json
import re
from urllib.parse import urlparse
def is_valid_url(url):
# Simple URL validation
parsed = urlparse(url)
return all([parsed.scheme, parsed.netloc])
def scrape_website(url, key_value):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return {}
soup = BeautifulSoup(response.content, 'html.parser')
json_array = []
articles = soup.find_all('article')
for article in articles:
description = article.find('p')
description_text = description.text.strip() if description else "No description available"
refsyn_sections = article.find_all('section', class_='refsyn')
for refsyn_section in refsyn_sections:
command = refsyn_section.find('p')
command_text = command.text.strip() if command else "Unknown Command"
example_sections = article.find_all('section', class_='example command_examples')
examples_text = ""
for example_section in example_sections:
pre_tags = example_section.find_all('pre', class_='pre codeblock')
for pre_tag in pre_tags:
pre_text = pre_tag.get_text().replace('\u00a0', ' ')
examples_text += pre_text + '\n'
json_object = {
"command": command_text,
"description": description_text,
"example": examples_text.strip()
}
if json_object["command"].startswith("show"):
json_array.append(json_object)
return {key_value: json_array}
def main():
json_array = []
while True:
webpage_url = input("Enter the URL of the website to parse data from:\n")
if not is_valid_url(webpage_url):
print("Invalid URL. Please enter a valid URL.")
continue
key = input("Enter the name for the data that will be scraped from the webpage:\n").strip()
if not key:
print("Key cannot be empty.")
continue
data = scrape_website(webpage_url, key)
if data:
json_array.append(data)
continue_loop = input("Would you like to parse from another page? (yes/no): ").strip().lower()
if continue_loop != "yes":
break
try:
with open('output.json', 'w') as file:
json.dump(json_array, file, indent=4)
print("Data saved to output.json successfully.")
except IOError as e:
print(f"Error writing to output.json: {e}")
if __name__ == "__main__":
main()