爬取网易新闻

403次阅读
没有评论
爬取网易新闻

爬取网易新闻

wangyi.py

import scrapy from selenium import webdriver

from wangyiPro.items import WangyiproItem

''' 可以尝试用这个项目做boss直聘的项目 python期末作业 空气质量分析也可以参考 ''' class WangyiSpider(scrapy.Spider): name = 'wangyi' # allowed_domains = ['www.wngyi.com'] start_urls = ['https://news.163.com/'] model_urls = []

# 实例化浏览器对象 def __init__(self): self.bro = webdriver.Chrome(executable_path='D:Python work space ReptileScrapy框架chromedriver.exe')

def parse(self, response): li_list = response.xpath('//*[@id="index2016_wrap"]/div[1]/div[2]/div[2]/div[2]/div[2]/div/ul/li') # alist = [3,4,6,7,8] alist = [3] for index in alist: model_url = li_list[index].xpath('./a/@href').extract_first() self.model_urls.append(model_url)

# 依次对每一个板块的页面进行请求 for url in self.model_urls: yield scrapy.Request(url,callback=self.parse_model)

# 每一个板块对应的新闻标题相关的内容都是动态加载的 # 解析每一个板块页面中对应新闻的标题和新闻详情页的url def parse_model(self,response): div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div') for div in div_list: title = div.xpath('./div/div[1]/h3/a/text()').extract_first() new_detail_url = div.xpath('./div/div[1]/h3/a/@href').extract_first() item = WangyiproItem() item['title'] = title # 利用meta将item传递给 # 对新闻详情页的url发起请求 yield scrapy.Request(url=new_detail_url,callback=self.parse_detail,meta={'item':item}) break # 解析新闻内容 def parse_detail(self,response): content = response.xpath('//*[@class="post_body"]//text()').extract() content = ''.join(content) item = response.meta['item'] item['content'] = content

yield item

def closed(self,spider): self.bro.quit()

middlewares.py

# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter from scrapy.http import HtmlResponse

import time

class WangyiproDownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects.

def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware.

# Must either: # – return None: continue processing this request # – or return a Response object # – or return a Request object # – or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None # 该方法拦截五大板块对应的响应对象,进行篡改 def process_response(self, request, response, spider): # spider爬虫对象 爬虫文件中实例化单独对象 # 挑选出指定的响应对象进行篡改 # 通过url指定request # 通过request指定response bro = spider.bro # 获取了在爬虫类中定义的浏览器对象

if request.url in spider.model_urls: bro.get(request.url) # 对五大板块对应的url进行请求 time.sleep(3) page_text = bro.page_source # 包含动态加载的数据

# response 五大板块对应的响应数据 # 针对定位到的这些response进行篡改 # 实例化一个新的响应对象(符合要求的:包含动态架加载出来的新闻数据) 取代原来的旧数据 # 基于selenium便捷的获取动态加载数据 new_response = HtmlResponse(url=request.url,body=page_text,encoding='utf-8',request=request) return new_response else: return response

def process_exception(self, request, exception, spider):

pass

pipelines.py

# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

# useful for handling different item types with a single interface from itemadapter import ItemAdapter

class WangyiproPipeline: # 进行持久化存储 def process_item(self, item, spider): with open('./wangyi.txt','w',encoding='utf-8') as fp: fp.write(item['title']+item['content']) print("item['title']"+item['title'])

print("item['content']"+item['content']) return item

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-28发表,共计3550字。
新手QQ群:570568346,欢迎进群讨论 Python51学习