引用库
from bs4 import BeautifulSoup #网页解析,获取数据
import re #正则表达式,进行文字匹配
import urllib.request,urllib.error #制定URL,获取网页数据
import xlwt #进行excel操作
import sqlite3 #进行SQLite数据库操作
获取网页内容
#得到指定URL的网页内容
def askURL(url):
head = {"User-Agent":""}
#模拟浏览器头部信息,向服务器发送消息
request = urllib.request.Request(url,headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
利用正则表达式提取想要的数据
#创建正则表达式对象,表示规则(字符串模式)
findlink = re.compile(r'<a href="(.*)">')
findphoto = re.compile(r'src="(.*?)"')
def getDate(baseurl):
datelist = []
for i in range(0,10):
url=baseurl+str(i*25)
#baseurl+"i*25"
html = askURL(url)
soup = BeautifulSoup(html,"html.parser")
for item in soup.find_all('div',class_="item"): #查找符合要求的字符串,形成列表
date = []
link = re.findall(findlink,item) #re库通过正则表达式查找指定字符串
date.append(link)
datelist.append(date)
return datelist
将获取的内容保存到excel表
def saveDate(savepath,Datelist):
print("save")
book = xlwt.Workbook(encoding="utf-8",style_compression=0) #创建workbook对象
sheet = book.add_sheet('top250',cell_overwrite_ok=True) #创建工作表
crl=("1","2","3")
for i in range(0,3):
sheet.write(0,i,crl[i])
for i in range(1,251):
for j in range(0,3):
sheet.write(i,j,Datelist[i-1][j])
book.save(savepath)