网络爬虫——豆瓣电影排行榜数据抓取(高级)
程序员文章站
2022-07-04 10:27:34
...
网络爬虫——豆瓣电影排行榜数据抓取(高级)
目标网址:
豆瓣电影排行:https://movie.douban.com/top250?start=
目标数据描述:排名、电影名称、导演、主演、评价人数等信息,将尽可能多的数据抓取保存
任务明细:
(1)使用requests库实现该网站网页源代码的获取;
(2)使用BeautifulSoup对获取的源代码进行解析,并成功找到目标数据所在的特定标签,进行网页结构的解析;
(3)定义函数,将获取的目标数据打印输出,有能力的同学可以试着将结果写入文件中。
(4)使用框架式结构,通过参数传递实现整个特定数据的爬取。
可以选择定义全局列表,将目标数据获取后添加到列表中,同时,注意观察分页时url的变化,以便获取整个的排行榜数据。建议通过for循环传递变化参数实现。
源码
import requests
from bs4 import BeautifulSoup
import bs4
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_encoding
result=(result.text.replace('<br>','')).replace('<br/>','')
return result
except:
return ""
def findUniverse(ulist , html):
soup = BeautifulSoup(html,"html.parser")
list_ = [0,0,0,0,0,0,0]
for li in soup.find(attrs=['class','grid_view']).children:
if isinstance(li ,bs4.element.Tag):
list_[0] = li.find('em').string
list_[1] = li.find(attrs=['class','title']).string
list_[2] = li.find(attrs=['class','bd']).find(attrs=['class','']).string.strip().split(" ")[1].replace(" ",'')
list_[3] = li.find(attrs=['class','bd']).find(attrs=['class','']).string.strip().split(" ")[4].replace(" ",'')
list_[4] = li.find(attrs=['class','star']).span.find_next_sibling().string.strip()
list_[5] = li.find(attrs=['class','star']).span.find_next_sibling().find_next_sibling().find_next_sibling().string.strip()
if li.find(attrs=['class','quote']) is not None:
list_[6] = li.find(attrs=['class','quote']).span.string
else:
list_[6] = None
ulist.append([list_[0],list_[1],list_[2],list_[3],list_[4],list_[5],list_[6]])
def printUniverse(ulist):
tplt = '{0:^4}\t{1:^10}\t{2:10}\t{3:10}\t{4:10}\t{5:10}'
print(tplt.format("排名","电影名称","导演","主演","评分","评价人数",chr(12288)))
for i in range(len(ulist)):
u = ulist[i]
print(tplt.format(u[0],u[1],u[2],u[3],u[4],u[5],chr(12288)))
def main():
ulist = []
for i in range(10):
url = 'https://movie.douban.com/top250?start=' + str( 25 * i )
html = getHtmlText(url)
findUniverse(ulist,html)
printUniverse(ulist)
main()
输出如下: