网络爬虫——票房网数据抓取及MYSQL存储
生活随笔
收集整理的這篇文章主要介紹了
网络爬虫——票房网数据抓取及MYSQL存储
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
網絡爬蟲——票房網數據抓取及MYSQL存儲
實驗內容
目標網站:電影票房網
目標網址:http://58921.com/daily/wangpiao
任務要求
目標數據:(1)名次(2)電影名稱 (3)日期(4)票房 (5)總場次(6)廢場(7)人次(8)上座率(9)票價
要求
(1)使用urllib或requests庫實現該網站網頁源代碼的獲取,并將源代碼進行保存;
(2)自主選擇re、bs4、lxml中的一種解析方法對保存的的源代碼讀取并進行解析,成功找到目標數據所在的特定標簽,進行網頁結構的解析;
(3)定義函數,將獲取的目標數據保存到MYSQL庫文件中。
(4)使用框架式結構,通過參數傳遞實現整個特定數據的爬取。
源碼
import requests import json import csv from requests.exceptions import RequestException from lxml import etree import pymysql from PIL import Image import pytesseract import traceback def connectMysql():return pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')def createMysqlTable():db = connectMysql()cursor = db.cursor()# fieldnames = ['名次','電影名稱','日期','票房','總場次','廢場','人次','上座率','票價']sql = 'create table if not exists movies (\名次 int not null ,\電影名稱 varchar(255) not null ,\日期 varchar(255) not null,\總場次 varchar(255) not null,\廢場 varchar(255) not null,\人次 varchar(255) not null,\上座率 varchar(255) not null,\票價 varchar(255) not null,\票房 varchar(255) not null,\primary key(名次))'cursor.execute(sql)print('ok')db.close()def getHtmlText(url):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 Edg/80.0.361.69' }try:result = requests.get(url,headers=headers,timeout=30)result.raise_for_status()result.encoding = result.apparent_encodingreturn result.textexcept:return ""def parsePage(html):ulist = []clist = []rlist = []ilist = []newhtml =etree.HTML(html,etree.HTMLParser())result=newhtml.xpath('//*[@id="content"]/div[2]/table/tbody/tr/td//text()')imgs = newhtml.xpath('//*[@id="content"]/div[2]/table/tbody/tr/td/a/img/@src', stream=True)j = 0 for img in imgs:j=j+1with open(str(j)+'.png', 'wb') as fd:picture=requests.get(img).contentfd.write(picture) for i in range(len(imgs)): str_ = str(i+1)+'.png'text = pytesseract.image_to_string(Image.open(str_))ilist.append(text.replace(" ",".").replace("M","億").replace("a","億")) # print(ilist) for i in range(len(result)):ulist.append(result[i].replace(" ","").replace('\r',"").replace("\n",''))while '' in ulist:ulist.remove('')length = len(ulist)weight = int(length / 8 )for i in range(weight):for j in range(8):clist.append(ulist[i*8+j])clist.append(ilist[i])rlist.append(clist)clist = []return rlistdef mysqlData(datas):table = 'movies'keys = '名次,電影名稱,日期,總場次,廢場,人次,上座率,票價,票房'db = connectMysql()cursor = db.cursor()for data in datas:values = ','.join(['%s']*len(data))sql = 'INSERT INTO {table}({keys}) VALUES({values})'.format(table=table,keys = keys ,values = values)print(sql)print(tuple(data))try :if cursor.execute(sql, tuple(data)):print("Succcessful")db.commit()except:traceback.print_exc()print("Failed")db.rollback()db.close()def main():createMysqlTable()url="http://58921.com/daily/wangpiao"html=getHtmlText(url)rlist=parsePage(html)mysqlData(rlist)main()結果輸出效果:
總結
以上是生活随笔為你收集整理的网络爬虫——票房网数据抓取及MYSQL存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 针对PVS方式的VDI部署趋势杀毒优化方
- 下一篇: word制表符怎么设置(word制表符详