-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrawler.py
More file actions
52 lines (42 loc) · 1.4 KB
/
crawler.py
File metadata and controls
52 lines (42 loc) · 1.4 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
import pymysql
import requests
from bs4 import BeautifulSoup
import time
import config
def fetch_titles_and_details(page_number):
url = f"http://18children.president.pa.go.kr/our_space/fairy_tales.php?srh%5Bcategory%5D=07&srh%5Bpage%5D={page_number}"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
titles = [title.text.strip().replace(" ", "") for title in soup.select(".title > a")]
details = [content.text.strip() for content in soup.select(".txt > a")]
return titles, details
def main():
start = time.time()
maximum_page = 20
titles = []
details = []
for page_number in range(1, maximum_page + 1):
page_titles, page_details = fetch_titles_and_details(page_number)
titles.extend(page_titles)
details.extend(page_details)
end = time.time()
print(f"{end - start:.5f} sec")
print(titles)
print(details)
# Connect to database
db = pymysql.connect(
host='localhost',
user='jenga',
password=config.database_password,
database='jenga',
charset='utf8'
)
cursor = db.cursor()
cursor.execute("TRUNCATE TABLE book")
insert_query = "INSERT INTO book (title, detail) VALUES (%s, %s)"
for title, detail in zip(titles, details):
cursor.execute(insert_query, (title, detail))
db.commit()
db.close()
if __name__ == '__main__':
main()