爬取(豆瓣电影 Top 250)排名前250名的电影名称
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# -*- condeing = utf-8 -*- # @Time:2021/7/19 20:40 # @Author : lmb # @File:.py # @Software: import urllib.request,urllib.error import re from bs4 import BeautifulSoup #爬取多条(实例:豆瓣TOP250) def GetUrl(baseurl): #1.爬取网页 for i in range(0,10): url=baseurl+str(i*25)#根据网页网址的规律例如:start=0? html=AskUrl(url)#保存获取的网页源码 #2.逐一解析数据 soup=BeautifulSoup(html,"html.parser") for item in soup.find_all('div',class_="hd"):#div里class为“hd”的,其实也就是所需要的数据所在的标签区 #print(item) data=[] #保存一部电影的信息 item=str(item)#将其转换为string类型 name=re.findall(findName,item)[0] #[0]的意思是只要提取每个标签的出现的第一个相匹配的 print(name)#打印出爬取的电影名称 #爬取网页 def AskUrl(url):#获取html源码 #模拟浏览器读取网页 head={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4542.2 Safari/537.36"} reqs=urllib.request.Request(url,headers=head)#对其进行封装 html=""; try: resposed=urllib.request.urlopen(reqs)#打开request封装好的reps html=resposed.read().decode("utf-8")#用read()读取 except urllib.error.URLError as e:#可能会报错的一些情况 if hasattr(e,"code"): print(e.code) if hasattr(e,"reason"): print(e.reson) return html#必须返回一个读取出来的对象 if __name__ == '__main__': findName=re.compile(r'(.*?)')#获取电影名的正则表达式 GetUrl("https://movie.douban.com/top250?start=")#用GetUrl的方法,得到爬取的排名前250的电影名称 |