| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [View Raw Code] [Original HTTPS Page] |
Scrapy 提供 日志(log) 功能, 可以通过 logging 模块使用。可以修改配置文件 settings.py ,任意位置添加 以下两行
LOG_FILE = "text.log"
LOG_LEVEL = "INFO"Log levels : Scrapy 提供 5 层 logging 级别
logging 设置 : 通过 settings.py 内进行以下设置可以配置 logging
Robots 协议 (网络爬虫排除标准 Robots Exclusion Protocal) : 网站通过 robots 协议告诉搜索引擎网页是否可被抓取,以及抓取标准
scrapy 默认准守该协议, 将 settings.py 进行修改 : ROBOTSTXT_OBER = False
虎扑新闻 robots : https://www.hupu.com/robots.txt
User-agent: * Allow: / Sitemap: https://bbs.hupu.com/sitemap_index.xml Sitemap: https://bbs.hupu.com/sitemap/sitemap_boards.xml Sitemap: https://voice.hupu.com/sitemap_index.xml Sitemap: https://nba.hupu.com/players/index.xml
实现分页
class HupuSpiderSpider(scrapy.Spider):
name = 'hupu_spider'
# 二次请求过滤的域名, 可以注释
# allowed_domains = ['www']
start_urls = []
for i in range(1, 101):
base_url = f"http://voice.hupu.com/news?category=all&page={i}"
start_urls.append(base_url)更改 settings.py
设置请求头
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/86.0.4240.111 Safari/537.36',
}允许 ROBOTS 协议
# Obey robots.txt rules
ROBOTSTXT_OBEY = False在 parse 实现提取逻辑
数据保存
在 parse 方法内 yield item
def parse_detail(self, response):
news_title = response.xpath('//h1[@class="headline"]/text()').extract_first()
news_source = response.xpath('//span[@id="source_baidu"]/a/text()').extract_first()
news_data = response.xpath('//span[@id="pubtime_baidu"]/text()').extract_first()
news_content = response.xpath('string(//div[@class="artical-main-content"])').extract_first()
item = HupuNewsItem()
item['news_url'] = response.url
item['news_title'] = news_title
item['news_source'] = news_source
item['news_data'] = news_data
item['news_content'] = news_content
yield item更改 item 定义 : 使用 item.py 内重定义
class HupuNewsItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
news_url = scrapy.Field()
news_title = scrapy.Field()
news_source = scrapy.Field()
news_data = scrapy.Field()
news_content = scrapy.Field()在 pipelines.py 内编写保存
class HupuNewsPipeline:
def __init__(self):
self.client = pymongo.MongoClient()
self.db = self.client['hupu_news']
def process_item(self, item, spider):
self.db['NBA'].update({'news_url': item['news_url']}, {'$set': dict(item)}, True)
print(item)
return item在 setting.py 内配置 pipelines 管道
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'hupu_news.pipelines.HupuNewsPipeline': 300,
}在 spiders 目录下 新建 main.py : 方便执行代码,只需要直接执行 main.py 即可执行爬虫
from scrapy import cmdline
cmdline.execute('scrapy crawl company_spider'.split())| Back | FazBrowse Home | New Git URL |