[TIL] Python, MongoDB & Web Crawling
03/01/23
![[TIL] Python, MongoDB & Web Crawling](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1677564532075%2Fb360cf82-c5f2-4f87-ac14-9b9d2d4a731c.png&w=3840&q=75)
Today, I learned how to crawl websites using the Beautiful Soup Python library. In addition, I created a MongoDB account and utilized PyMongo and dnspython to add, find, modify, and delete data in the database. Web crawling is a powerful tool that enables anyone to extract data from any website and transform it into a secondary product.
Python Virtual Environment
To keep dependencies required by different projects or locals separate by creating isolated python virtual environments for them
Install (on Git Bash):
python -m venv venvNameActivate (on Git Bash):
source venvName/Scripts/activate
Using pip - package installer in Python
By using
pip install packageName, we can use a bunch of Python libraries that others already created for the useful featuresError I encountered
After importing
requestslibrary, it shows the following error:ModuleNotFoundErrorHow to resolve
I tried to uninstall Python 3.10 version that I used and install Python 3.8 since Python 3.10 is newly updated, which is likely to be less compatible with some libraries
By [Windows+R], on the command line, I
pip install requestsunder the Python Scripts path.
Python Web Crawling
- Install beautifulSoup4:
pip install bs4
# Base format
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
Select the HTML element from the browser
Chrome Extension > Inspect Element > Right-click the data I want to crawl > Copy > Copy Selector (looks like this:
#old_content > table > tbody > tr:nth-child(3) > td.title > div > a)trs = soup.select('#old_content > table > tbody > tr') for tr in trs: movie = tr.select_one('td.title > div > a') if movie is not None: print(movie.text)
Exercise: music chart top 50 crawling
import requests from bs4 import BeautifulSoup headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'} data = requests.get('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20221201',headers=headers) soup = BeautifulSoup(data.text, 'html.parser') trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr') for tr in trs: title = tr.select_one('td.info > a.title.ellipsis').text.strip() rank = tr.select_one('td.number').text[0:2].strip() singer = tr.select_one('td.info > a.artist.ellipsis').text.strip() print(rank, title, singer)
Database: MongoDB - NoSQL
Install packages to import MongoDB in Python:
pip install pymongo dnspythonpymongobase formatfrom pymongo import MongoClient client = MongoClient('mongodb+srv://siwon:<password>@cluster0.icysouv.mongodb.net/?retryWrites=true&w=majority') db = client.dbsiwonHow to add data
doc = { 'name': 'Tom', 'age': 24 } db.users.insert_one(doc)
How to bring data from DB
# every data all_users = list(db.users.find({},{'_id':False})) print(all_users[0]) print(all_users[0]['name']) for a in all_users: print(a) # specific data user = db.users.find_one({}) print(user)How to modify data
db.users.update_one({'name':'Tom'},{'$set':{'age':19}})How to delete data
db.users.delete_one({'name':'Tom'})
![[코테] 그리디 문제 - 무지의 먹방 라이브](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1712215455263%2F1ac1f35a-8862-4e42-8d0c-e2bea01e04c0.png&w=3840&q=75)
![[코테] Bfs 토마토](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709032619170%2F70056896-c857-444b-9c99-45bfcb466806.png&w=3840&q=75)
![[코테] Dfs 문제 유형 - 그래프 내에서 구분하여 카운트 하기](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709019361383%2Fb0585d72-c808-4169-83a9-2724f312e927.png&w=3840&q=75)
![[코테] DFS vs BFS](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971211123%2F71f9386c-6a62-43b2-a602-4d084c24d6cf.png&w=3840&q=75)
![[코테] 여행경로](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971251412%2F27ce72ed-8ee7-4d13-a02f-ff4bbe50c4be.png&w=3840&q=75)