程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python reptile practice -- Chapter 1: crawling Douban movie top250

編輯:Python

This practical project has passed python Crawling for Douban movie Top250 The list , utilize flask frame and Echarts Chart Analysis score 、 Release year and visualize results , And made The word cloud , The project has been uploaded to the server , Welcome to criticize and correct .

Project presentation :http://121.36.81.197:5000/
Source code address :https://github.com/lzz110/douban_movies_top250
Learning materials :Python Reptile technology 5 It's a quick success (2020 New collection )

Project technology stack :Flask frame 、Echarts、WordCloud、SQLite
Environmental Science :Python3
development tool :PyCharm

Chapter one : Crawl data 、 preservation

Crawling Links : https://movie.douban.com/top250

excel And database files :excel And database file download

  • Library files used
from bs4 import BeautifulSoup # Web page parsing , get data 
import re # Regular expressions , Match with text 
import xlwt # To develop URL, Get web data 
import urllib.request, urllib.error # Conduct excel operation 
import sqlite3 # Conduct sqlite Database operation 
  • Simulate browser header information , Send a message to the server , Get web information
    If the server response code is 418, Description the request was unsuccessful , The website does not allow crawlers , So simulate the browser header information :User-Agent Passed on to get Functional headers Parameters , The result returned to 200, Indicates that the request was successful , The code is :
def askURL(url):
head = {
 # Simulate browser header information , Send a message to the server 
"User-Agent": " Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 83.0.4103.116Safari / 537.36"
} # Tell the browser what level of file content we accept 
request = urllib.request.Request(url, headers=head)
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
# print(html)
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
  • According to the web information utilize Regular expressions Data analysis
def getData(baseurl):
datalist = []
for i in range(0, 10):
url = baseurl + str(i * 25)
html = askURL(url) # Save the crawled web page source code 
# Parse the data one by one 
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all('div', class_="item"):
# print(item) # test 
data = [] # preservation 
item = str(item)
# re Library regular expression to find the specified string , Form a list 
Link = re.findall(findLink, item)[0] # link 
# print(Link)
data.append(Link)
ImaSrc = re.findall(findImaSrc, item)[0] # Picture links 
# print(ImaSrc)
data.append(ImaSrc)
Title = re.findall(findTitle, item)[0] # title : There may only be one Chinese name , There is no translated name 
if (len(Title) == 2):
# print(" complete title="+Title)
cTitle = Title[0] # Add Chinese name 
# print(cTitle)
data.append(Title)
oTitle = Title[1].replace("/", "") # Translated title 
# print(oTitle)
# data.append(' ')
else:
data.append(Title)
# data.append(' ')
# print(Title)
Rating = re.findall(findRating, item)[0] # score 
data.append(Rating)
Judge = re.findall(findJudge, item)[0] # Number of evaluators 
data.append(Judge)
Inq = re.findall(findInq, item) # summary 
if len(Inq) != 0:
Inq = Inq[0].replace(".", "") # Remove the full stop 
data.append(Inq)
else:
data.append(" ") # leave a blank 
Bd = re.findall(findBd, item)[0] # Related content 
temp = re.search('[0-9]+.*\/?', Bd).group().split('/')
year, country, category = temp[0], temp[1], temp[2] # Get the year 、 region 、 type 
data.append(year)
data.append(country)
data.append(category)
datalist.append(data) # Put the processed information of a movie into datalist
return datalist

Save the crawl result data in two formats ( database and excel form ):

  • write in excel
def saveData(datalist, savepath):
print("save...")
book = xlwt.Workbook(encoding="utf-8") # establish workbook object 
sheet = book.add_sheet(' Watercress movie Top250', cell_overwrite_ok=True) # Create sheet 
# Make header 
col = (" Movie details link ", " Picture links ", " Chinese name ", " score ", " Evaluation number ", " summary ", " Release year "," Producer country "," type ")
for i in range(0, len(col)):
sheet.write(0, i, col[i])
for i in range(0, 250):
# print(" The first %d strip "%(i+1))
data = datalist[i]
for j in range(0, len(col)):
sheet.write(i + 1, j, data[j])
book.save(savepath) # preservation 

Save to excel result :

  • Write to database
def saveData2DB(datalist, dbpath):
init_db(dbpath)
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
for data in datalist:
for index in range(len(data)):
data[index] = '"' + data[index] + '"'
sql = ''' insert into movie250( info_link, pic_link, cname, score,rated, introduction,year_release,country,category ) values(%s)''' % ",".join(data)
# print(sql)
cur.execute(sql)
conn.commit()
cur.close()
conn.close

Save to database results

This completes the crawling data section , The next chapter is Movie data processing and visualization


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved