鱼C论坛

 找回密码
 立即注册
查看: 1808|回复: 1

[作品展示] python爬虫练习

[复制链接]
发表于 2021-10-6 10:59:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
第一次尝试,用的PyCharm不是很熟练,社区版也没搞懂数据库怎么用,就只能用excel保存了



  1. # -*-codeing = utf-8 -*-
  2. # @Time : 2021/10/1 15:57
  3. # @Author : 有点冷丶
  4. # @File : pachong.py
  5. # @Software: PyCharm


  6. #引入模块
  7. from bs4 import BeautifulSoup     #网页解析
  8. import re      #正则表达式,文字匹配
  9. import urllib.request   #制定upl,获取网页数据
  10. import urllib.error
  11. import xlwt    #进行excel操作
  12. import sqlite3    #进行sqlite数据库操作

  13. def main():
  14.     baseurl = "http://movie.douban.com/top250?start="
  15.     #1.爬取网页
  16.     datalist = getData(baseurl)
  17.     #3.保存数据
  18.     savepath = r".\\豆瓣电影top250.xls"
  19.     saveData(datalist,savepath)    #保存到excel表格
  20.     dppath = "movie250.db"
  21.     #savedata2db(datalist,dbpath)   #保存到数据库


  22. #影片详情链接规则
  23. findLink = re.compile(r'<a href="(.*?)">')  #创建正则表达式对象,表示规则,字符串模式
  24. #影片图片的链接
  25. findImgSrc = re.compile(r'<img.*src="(.*?)"',re.S)
  26. #影片的片名
  27. findname = re.compile(r'<span class="title">(.*?)</span>')
  28. #影片的评分
  29. finddafen = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
  30. #评价人数
  31. findpeople = re.compile(r'<span>(\d*)人评价</span>')
  32. #找到概况
  33. findInq = re.compile(r'<span class="inq">(.*)</span>')
  34. #相关内容
  35. finddy = re.compile(r'<p class="">(.*?)</p>',re.S)





  36. #爬取网页
  37. def getData(baseurl):
  38.     datalist = []
  39.     for i in range(0,1):     #调用获取页面
  40.         url = baseurl + str(i*25)
  41.         html = askURL(url)    #保存获取到的网页源码
  42.         #print(html)
  43.     # 2.逐一解析数据
  44.         soup = BeautifulSoup(html,"html.parser")
  45.         for item in soup.find_all('div',class_="item"):  #查找符合要求的字符串,形成列表
  46.            #print(item)   #测试查看电影全部item信息
  47.             data = []    #保存一个电影的全部信息
  48.             item = str(item)

  49.             #影片详情超链接
  50.             link = re.findall(findLink,item)[0]     #re库
  51.             data.append(link)        #添加链接

  52.             imgSrc = re.findall(findImgSrc,item)[0]
  53.             data.append(imgSrc)      #添加图片

  54.             names = re.findall(findname,item)
  55.             if(len(names) == 2):
  56.                 cname = names[0]      #添加中文名
  57.                 data.append(cname)
  58.                 oname = names[1].replace("/","")    #去掉无关的符号
  59.                 data.append(oname)     #添加外国名
  60.             else:
  61.                 data.append(names[0])
  62.                 data.append('')   #外国名留空

  63.             dafen = re.findall(finddafen,item)[0]
  64.             data.append(dafen)     #添加评分

  65.             people = re.findall(findpeople,item)[0]
  66.             data.append(people)     #添加打分人数

  67.             inq = re.findall(findInq,item)   #添加概况
  68.             if len(inq) != 0:
  69.                 inq = inq[0].replace("。","")
  70.                 data.append(inq)  #添加概述
  71.             else:
  72.                 data.append("")  #留空

  73.             dy = re.findall(finddy,item)[0]  #添加相关内容
  74.             dy = re.sub('<br(\s+)?/>(\s+)?'," ",dy)
  75.             dy = re.sub('/'," ",dy)
  76.             data.append(dy.strip())    #strip去掉前后空格

  77.             datalist.append(data)     #把处理好的信息储存进datalist
  78.     #print(datalist, "\n")
  79.     return datalist




  80. #得到指定一个url的网页的内容
  81. def askURL(url):
  82.     head = {
  83.         "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31"
  84.             }
  85.                 #用户代理,伪装
  86.     request = urllib.request.Request(url,headers=head)
  87.     html = ""
  88.     try:
  89.         response = urllib.request.urlopen(request)
  90.         html = response.read().decode("utf-8")
  91.     except urllib.error.URLError as e:
  92.         if hasattr(e,"code"):
  93.             print(e.code)
  94.         if hasattr(e,"reason"):
  95.             print(e.reason)
  96.     return html





  97. #保存数据到excel
  98. def saveData(datalist,savepath):
  99.     print("save...")
  100.     book = xlwt.Workbook(encoding="utf-8",style_compression=0)  # 创建一个workbook对象
  101.     sheet = book.add_sheet('豆瓣电影top250',cell_overwrite_ok=True)  # 创建工作表
  102.     col = ("电影详情链接","图片链接","影片中文名","影片外国名","评分","评价数","概况","相关信息")
  103.     for i in range(0,8):
  104.         sheet.write(0,i,col[i])  #列名
  105.     for i in range(0,250):
  106.         print("第%d条"%(i+1))
  107.         data = datalist[i]
  108.         for j in range(0,8):
  109.             sheet.write(i+1,j,data[j])

  110.     book.save(savepath)  # 保存数据表

  111. #保存到数据库
  112. def savedata2db(datalist,dbpath):
  113.     init_db(dbpath)
  114.     conn = sqlite3.connect(dbpath)
  115.     cur = conn.cursor()
  116.     for data in datalist:
  117.         for index in range(len(data)):
  118.             if index == 4 or index == 5:
  119.                 continue
  120.             data[index] = '"'+data[index]+'"'
  121.         sql = '''
  122.                 insert into movie250(
  123.                 info_link,pic_link,cname,ename,score,rated,introduction,info)
  124.                 values(%s)'''%",".join(data)
  125.         cur.execute(sql)
  126.         conn.commit()
  127.     cur.close()
  128.     conn.close()
  129.                
  130. #创建数据库
  131. def init_db(dbpath):
  132.     sql = '''
  133.         create table movie250
  134.         (
  135.         id integer primary key autoincrement,
  136.         info_link text,
  137.         pic_link text,
  138.         cname varchar,
  139.         ename varchar,
  140.         score numeric,
  141.         rated numeric,
  142.         introduction text,
  143.         info text
  144.         )
  145.       '''
  146.     conn = sqlite3.connect(dbpath)
  147.     cursor = conn.cursor()
  148.     cursor.execute(sql)
  149.     conn.commit()
  150.     conn.close()




  151. if __name__ == "__main__":
  152.     main()
  153.     #init_db("test.db")   #测试数据库
  154.     print("爬取完毕")
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-10-6 11:12:09 | 显示全部楼层
pycharm社区版本不支持大部分第三方库
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-16 17:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表