python爬虫 完整代码
python,爬虫,完整,代码
2025-04-01 16:27:54 时间
大家好,又见面了,我是你们的朋友全栈君。
python爬虫 完整代码
使用Python爬取豆瓣top250的相关数据,并保存到同目录下Excel
import re
import urllib.error
import urllib.request
import xlwt
from bs4 import BeautifulSoup
def main():
baseurl ="https://movie.douban.com/top250?start=/"
datelist = getDate(baseurl)
savepath=".\\douban.xls"
saveDate(datelist,savepath)
# askURL("https://movie.douban.com/")
findlink = re.compile(r'<a href="(.*?)">')
findimg = re.compile(r'<img.*src="(.*?)"',re.S)
findtitle = re.compile(r'<span class="title">(.*)</span')
findrating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span')
findjudge = re.compile(r'<span>(\d*)人评价</span>')
findinq= re.compile(r'<span class="inq">(.*)</span>')
def getDate(baseurl):
datalist =[]
for i in range(0,10):
url=baseurl+str(i*25)
html=askURL(url)
soup = BeautifulSoup(html,"html.parser")
for item in soup.find_all('div',class_="item"):
data = []
item = str(item)
link = re.findall(findlink,item)[0]
data.append(link)
img=re.findall(findimg,item)[0]
data.append(img)
title=re.findall(findtitle,item)[0]
rating=re.findall(findrating,item)[0]
data.append(rating)
judge=re.findall(findjudge,item)[0]
data.append(judge)
inq=re.findall(findinq,item)
if len(inq)!=0:
inq=inq[0].replace("。","")
data.append(inq)
else:
data.append(" ")
print(data)
datalist.append(data)
print(datalist)
return datalist
def askURL(url):
head = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"}
request=urllib.request.Request(url,headers=head)
html=""
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
def saveDate(datalist,savepath):
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('豆瓣电影',cell_overwrite_ok=True)
col =("电影详情","图片","影片","评分","评价数","概况")
for i in range(0,5):
worksheet.write(0,i,col[i])
for i in range(0,250):
print("第%d条" %(i+1))
data=datalist[i]
for j in range(0,5):
worksheet.write(i+1,j,data[j])
workbook.save(savepath)
if __name__ == '__main__':
main()
print("爬取完毕")
直接复制粘贴就行。 若要更改爬取网站,则需要更改URL以及相应的html格式(代码中的“item”)
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/134562.html原文链接:https://javaforall.cn
相关文章
- Python 爬虫 NO.1 URI和URL
- 全网最全python爬虫精进
- 终于来了, 彭涛Python 爬虫训练营 !爬虫福利倒计时,速度,下周涨价!
- origin安装嵌入python_python爬虫之git的使用(origin说明)
- Python - 手把手教你用Scrapy编写一个爬虫
- Python爬虫之scrapy框架
- Python爬虫之urllib
- Python实现 —【简易】12306爬虫[通俗易懂]
- 终于来了, 彭涛Python 爬虫训练营 !爬虫课福利进行中,务必不要错过!
- Python爬虫之xpath语法及案例使用
- Python招聘岗位信息聚合系统源码(爬虫爬取、数据分析、可视化、互动等功能)
- Python爬虫之多线程
- Python爬虫之fiddler手机抓包
- Python爬虫之requests
- 终于来了, 彭涛Python 爬虫训练营 !本周最低价,这次千万别错过了!
- [Python 爬虫]煎蛋网 OOXX 妹子图爬虫(1)——解密图片地址
- python 网络爬虫入门(一)———第一个python爬虫实例
- python和pythoncharm有什么区别_python为什么叫爬虫
- Python 万能代码模版:爬虫代码篇「建议收藏」
- mac pycharm安装设置_python爬虫 | mac系统PyCharm的安装「建议收藏」