Python高级应用程序设计任务要求
用Python实现一个面向主题的网络爬虫程序,并完成以下内容:
(注:每人一题,主题内容自选,所有设计内容与源代码需提交到博客园平台)
一、主题式网络爬虫设计方案(15分)
1.主题式网络爬虫名称
瓜子二手车网站数据爬取
2.主题式网络爬虫爬取的内容与数据特征分析
品牌、车型、年月、公里数、售价
爬取内容:汽车品牌、汽车款式、上牌时间、行驶里程数、排放标准、二手价格和同款新车的参考价格
3.主题式网络爬虫设计方案概述(包括实现思路与技术难点)
爬取瓜子二手车数据实现思路:使用requests库爬取数据、生成所有需要抓取的URL,对所有目标链接进行数据抓取,存储数据
爬取瓜子二手车数据技术难点:瓜子二手车网运用的反爬虫措施主要有js混淆,根据发送的原始header和js混淆生成特定的cookie才能访问到网站。
deal_head.py处理的数js混淆和生成特定的header。原始header的user-agent必须是使用电脑相同的平台(windows、linux),不一致返回不了有效的cookie。
二、主题页面的结构特征分析(15分)
1.主题页面的结构特征
2.Htmls页面解析
主题页面为瓜子二手车网站宝马检索结果的HTML代码,需要的信息保存在carlist选择器属性的标签中
页数内容在该结构中,以此分析如何按页爬取所需要的数据
3.节点(标签)查找方法与遍历方法
(必要时画出节点树结构)
→
- →
-
三、网络爬虫程序设计(60分)
爬虫程序主体要包括以下各部分,要附源代码及较详细注释,并在每部分程序后面提供输出结果的截图。
1.数据爬取与采集# 导入第三方包 import requests from bs4 import BeautifulSoup import time # 设置伪头 headers = { 'Accept':'*/*', 'Accept-Encoding':'gzip, deflate, br', 'Accept-Language':'zh-CN,zh;q=0.8', 'Connection':'keep-alive', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36' } # 二手车主页的链接 url = 'https://www.guazi.com/quanzhou/bmw/' # 发出抓取链接的请求并进一步解析 res = requests.get(url, headers = headers).text soup = BeautifulSoup(res,'html.parser') # 抓取二手车品牌名称及对应的链接 car_brands = soup.findAll('div',{'class':'brand-name'}) car_brands = [j for i in car_brands for j in i] brands = [i.text for i in car_brands] urls = ['https://www.guazi.com/quanzhou/bmw/' + i['href'] for i in car_brands] # 生成所需抓取的目标链接 target_urls = [] target_brands = [] for b,u in zip(brands,urls): # 抓取各品牌二手车主页下的所有页码 res = requests.get(u, headers = headers).text soup = BeautifulSoup(res,'html.parser') # 查询出页数 if len(soup.findAll('div',{'class':'the-pages'})) == 0: pages = 1 else: pages = int([page.text for page in soup.findAll('div',{'class':'the-pages'})[0].findAll('a')][-2]) time.sleep(3) for i in range(1,pages + 1): target_brands.append(b) target_urls.append(u+'?page='+str(i)+'#pagetag') # 构建空列表,用于数据的存储 brand = [] title = [] boarding_time = [] km = [] discharge = [] sec_price = [] new_price = [] # 对每个链接发生请求 for b,u in zip(target_brands,target_urls):
res = requests.get(u, headers = headers).text soup = BeautifulSoup(res,'html.parser') # 每页车子的数量 N = len([i.findAll('a')[0]['title'] for i in soup.findAll('div',{'class':'item_details'})]) try: # 车品牌 brands = (b+'-')*N brand.extend(brands.split('-')[:-1]) # 车名称 title.extend([i.findAll('a')[0]['title'] for i in soup.findAll('div',{'class':'item_details'})]) # 二手车的上牌时间、行驶里程数等信息 info = [i.findAll('li') for i in soup.findAll('ul',{'class':'ul_news'})] boarding_time.extend([i[0].text[4:] for i in info]) km.extend([i[1].text[4:] for i in info]) discharge.extend([i[3].text[4:]