13ze commited on
Commit
28d80c3
·
verified ·
1 Parent(s): caafb3c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import pandas as pd
5
+ import time
6
+ from random import randint
7
+ import gradio as gr
8
+
9
+ def scrape_data_with_retry(url, retries=3):
10
+ for attempt in range(retries):
11
+ try:
12
+ response = requests.get(url, timeout=10)
13
+ response.raise_for_status()
14
+ soup = BeautifulSoup(response.text, 'html.parser')
15
+
16
+ title = soup.find('title').text if soup.find('title') else 'N/A'
17
+ content = soup.find('div', class_='entry-content').text if soup.find('div', class_='entry-content') else 'N/A'
18
+ featured_image = soup.find('meta', property='og:image')['content'] if soup.find('meta', property='og:image') else 'N/A'
19
+ category = ', '.join([cat.text for cat in soup.find_all('a', rel='category tag')]) if soup.find_all('a', rel='category tag') else 'N/A'
20
+ tags = ', '.join([tag.text for tag in soup.find_all('a', rel='tag')]) if soup.find_all('a', rel='tag') else 'N/A'
21
+
22
+ return {'title': title, 'content': content, 'featured_image': featured_image, 'category': category, 'tags': tags}
23
+ except (requests.RequestException, ValueError) as e:
24
+ time.sleep(2 ** attempt + randint(0, 1000) / 1000)
25
+ return {'title': 'N/A', 'content': 'N/A', 'featured_image': 'N/A', 'category': 'N/A', 'tags': 'N/A'}
26
+
27
+ def scrape_all(urls):
28
+ scraped_data = []
29
+ for url in urls:
30
+ data = scrape_data_with_retry(url)
31
+ scraped_data.append(data)
32
+ time.sleep(randint(1, 3)) # Sleep to avoid overloading the server
33
+ return scraped_data
34
+
35
+ # Gradio interface
36
+ def scrape_interface(file):
37
+ scrape_links_df = pd.read_csv(file.name)
38
+ urls = scrape_links_df['URL'].tolist()
39
+ scraped_data = scrape_all(urls)
40
+ scraped_df = pd.DataFrame(scraped_data)
41
+ output_file_path = 'scraped_data.csv'
42
+ scraped_df.to_csv(output_file_path, index=False)
43
+ return output_file_path
44
+
45
+ demo = gr.Interface(
46
+ fn=scrape_interface,
47
+ inputs="file",
48
+ outputs="file",
49
+ title="Web Scraper",
50
+ description="Upload a CSV file containing URLs to scrape."
51
+ )
52
+
53
+ demo.launch(share=True)