Spaces:
Running
Running
Commit
·
504b4eb
1
Parent(s):
27030ce
prevent unhandled error when getting URL content
Browse files
scrape.py
CHANGED
|
@@ -9,20 +9,24 @@ def get_url_content(url: str) -> str:
|
|
| 9 |
:param url: The URL to retrieve content from.
|
| 10 |
:return: The content of the URL as a string.
|
| 11 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"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"
|
| 17 |
-
}
|
| 18 |
-
)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
return ""
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
| 9 |
:param url: The URL to retrieve content from.
|
| 10 |
:return: The content of the URL as a string.
|
| 11 |
"""
|
| 12 |
+
try:
|
| 13 |
+
response = requests.get(
|
| 14 |
+
url,
|
| 15 |
+
headers={
|
| 16 |
+
"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"
|
| 17 |
+
}
|
| 18 |
+
)
|
| 19 |
|
| 20 |
+
if response.status_code != 200:
|
| 21 |
+
print(f"Failed to retrieve content from {url}. Status code: {response.status_code} - {response.reason}")
|
| 22 |
+
return ""
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# parse the html content using BeautifulSoup
|
| 25 |
+
parser = BeautifulSoup(response.text, 'html.parser')
|
|
|
|
| 26 |
|
| 27 |
+
# extract text from the parsed HTML
|
| 28 |
+
return parser.text.strip() if parser.text else ""
|
| 29 |
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"An error occurred while retrieving content from {url}: {e}")
|
| 32 |
+
return ""
|