这篇文章咱们将使用 requests 和 xpath 爬取豆瓣电影 Top250,下面先贴上最终的效果图:html
咱们首先使用 Chrome 浏览器打开 豆瓣电影 Top250,很容易能够判断出网站是一个静态网页python
而后咱们分析网站的 URL 规律,以便于经过构造 URL 获取网站中全部网页的内容json
首页:https://movie.douban.com/top250浏览器
第二页:https://movie.douban.com/top250?start=25&filter=网络
第三页:https://movie.douban.com/top250?start=50&filter=dom
...工具
不难发现,URL 能够泛化为 https://movie.douban.com/top250?start={page}&filter=,其中,page 表明页数网站
最后咱们还须要验证一下首页的 URL 是否也知足规律,通过验证,很容易能够发现首页的 URL 也知足上面的规律编码
核心代码以下:url
import requests # 获取网页源代码 def get_page(url): # 构造请求头部 headers = { 'USER-AGENT':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } # 发送请求,得到响应 response = requests.get(url=url,headers=headers) # 得到网页源代码 html = response.text # 返回网页源代码 return html
接下来咱们开始分析每个网页的内容,并从中提取出须要的数据
使用快捷键 Ctrl+Shift+I
打开开发者工具,选中 Elements
选项栏分析网页的源代码
须要提取的数据包括(能够使用 xpath 进行匹配):
html.xpath('//div[@class="hd"]/a/@href')
html.xpath('//div[@class="hd"]/a/span[1]/text()')
html.xpath('//div[@class="bd"]/p[1]//text()')
html.xpath('//div[@class="bd"]/div/span[2]/text()')
html.xpath('//div[@class="bd"]/div/span[4]/text()')
核心代码以下:
from lxml import etree # 解析网页源代码 def parse_page(html): # 构造 _Element 对象 html_elem = etree.HTML(html) # 详细连接 links = html_elem.xpath('//div[@class="hd"]/a/@href') # 电影名称 titles = html_elem.xpath('//div[@class="hd"]/a/span[1]/text()') # 电影信息(导演/主演、上映年份/国家/分类) infos = html_elem.xpath('//div[@class="bd"]/p[1]//text()') roles = [j for i,j in enumerate(infos) if i % 2 == 0] descritions = [j for i,j in enumerate(infos) if i % 2 != 0] # 豆瓣评分 stars = html_elem.xpath('//div[@class="bd"]/div/span[2]/text()') # 评论人数 comments = html_elem.xpath('//div[@class="bd"]/div/span[4]/text()') # 得到结果 data = zip(links,titles,roles,descritions,stars,comments) # 返回结果 return data
下面将数据分别保存为 txt 文件、json 文件和 csv 文件
import json import csv # 打开文件 def openfile(fm): fd = None if fm == 'txt': fd = open('douban.txt','w',encoding='utf-8') elif fm == 'json': fd = open('douban.json','w',encoding='utf-8') elif fm == 'csv': fd = open('douban.csv','w',encoding='utf-8',newline='') return fd # 将数据保存到文件 def save2file(fm,fd,data): if fm == 'txt': for item in data: fd.write('----------------------------------------\n') fd.write('link:' + str(item[0]) + '\n') fd.write('title:' + str(item[1]) + '\n') fd.write('role:' + str(item[2]) + '\n') fd.write('descrition:' + str(item[3]) + '\n') fd.write('star:' + str(item[4]) + '\n') fd.write('comment:' + str(item[5]) + '\n') if fm == 'json': temp = ('link','title','role','descrition','star','comment') for item in data: json.dump(dict(zip(temp,item)),fd,ensure_ascii=False) if fm == 'csv': writer = csv.writer(fd) for item in data: writer.writerow(item)
下面是完整代码,也是几十行能够写完
import requests from lxml import etree import json import csv import time import random # 获取网页源代码 def get_page(url): headers = { 'USER-AGENT':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } response = requests.get(url=url,headers=headers) html = response.text return html # 解析网页源代码 def parse_page(html): html_elem = etree.HTML(html) links = html_elem.xpath('//div[@class="hd"]/a/@href') titles = html_elem.xpath('//div[@class="hd"]/a/span[1]/text()') infos = html_elem.xpath('//div[@class="bd"]/p[1]//text()') roles = [j.strip() for i,j in enumerate(infos) if i % 2 == 0] descritions = [j.strip() for i,j in enumerate(infos) if i % 2 != 0] stars = html_elem.xpath('//div[@class="bd"]/div/span[2]/text()') comments = html_elem.xpath('//div[@class="bd"]/div/span[4]/text()') data = zip(links,titles,roles,descritions,stars,comments) return data # 打开文件 def openfile(fm): fd = None if fm == 'txt': fd = open('douban.txt','w',encoding='utf-8') elif fm == 'json': fd = open('douban.json','w',encoding='utf-8') elif fm == 'csv': fd = open('douban.csv','w',encoding='utf-8',newline='') return fd # 将数据保存到文件 def save2file(fm,fd,data): if fm == 'txt': for item in data: fd.write('----------------------------------------\n') fd.write('link:' + str(item[0]) + '\n') fd.write('title:' + str(item[1]) + '\n') fd.write('role:' + str(item[2]) + '\n') fd.write('descrition:' + str(item[3]) + '\n') fd.write('star:' + str(item[4]) + '\n') fd.write('comment:' + str(item[5]) + '\n') if fm == 'json': temp = ('link','title','role','descrition','star','comment') for item in data: json.dump(dict(zip(temp,item)),fd,ensure_ascii=False) if fm == 'csv': writer = csv.writer(fd) for item in data: writer.writerow(item) # 开始爬取网页 def crawl(): url = 'https://movie.douban.com/top250?start={page}&filter=' fm = input('请输入文件保存格式(txt、json、csv):') while fm!='txt' and fm!='json' and fm!='csv': fm = input('输入错误,请从新输入文件保存格式(txt、json、csv):') fd = openfile(fm) print('开始爬取') for page in range(0,250,25): print('正在爬取第 ' + str(page+1) + ' 页至第 ' + str(page+25) + ' 页......') html = get_page(url.format(page=str(page))) data = parse_page(html) save2file(fm,fd,data) time.sleep(random.random()) fd.close() print('结束爬取') if __name__ == '__main__': crawl()
【爬虫系列相关文章】