糗事百科官网:https://www.qiushibaike.com/
段子网址:https://www.qiushibaike.com/text/
关于解析html博主选择的方法是使用xpath,如有不懂的同学,可看下面两个表格。如果想要深入学习xpath的相关知识可点击博主给的官方 文档的链接进行学习,博主在此声明是为了让读者们能够理解解析式的具体含义。
官网网址:https://lxml.de/tutorial.html
路径表达式
表达式 | 描述 |
---|---|
nodename | 选取此节点的所有子节点 |
/ | 从根节点选取 |
// | 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置 |
. | 选取当前节点 |
… | 选取当前节点的父节点 |
@ | 选取属性 |
匹配属性
通配符 | 描述 |
---|---|
* | 匹配任何元素节点 |
@* | 匹配任何属性节点 |
node() | 匹配任何类型的节点 |
根据上图标记部分可以看到我们主要的要点如下。
通过查看开发者选项,发现<div class ="coll old-style-coll">
这个标签对应的正是所有内容的整体存放位置,那么我们也可知道之后的所有内容都是从此标签的子标签内提取得到。
分析一番后,我们可以得到获取所有文本内容的解析式如下:
//div[@class = 'col1 old-style-col1']/div
由上图我们可以看到作者的位置在<h2></h2>
这个标签中。
分析一番后,我们可以得到获取作者的解析式如下:
.//h2//text()
由上图我们可以看到段子的位置在<div class ="content"></div>
这个标签中。
分析一番后,我们可以得到获取段子的解析式如下:
.//div[@class='content']//text()
由上图我们可以看到页面的位置在<ul class ="pagination"></ul>
这个标签中。
分析一番后,我们可以得到获取页面的解析式如下:
//ul[@class='pagination']/li[last()]/a/@href
在创建完成一个scrapy项目后,需要对settings进行一些修改
此处默认为True,需要修改为False。否则无法爬取内容。
取消此部分的注解并添加请求头,伪装自己的身份。
duanzidivs = response.xpath("//div[@class = 'col1 old-style-col1']/div")
print("=")
print(type(duanzidivs))
print("=")
通过运行我们可以发现其为SelectorList
类型
for duanzidiv in duanzidivs:
# strip() 去除前后的空白字符
author = duanzidiv.xpath(".//h2//text()").get().strip()
content = duanzidiv.xpath(".//div[@class='content']//text()").getall()
content = "".join(content).strip()
print(author)
print(content)
ITEM_PIPELINES
的限制class QsbkPipeline:
def __init__(self):
self.fp = open("duanzi.json","w",encoding="utf-8")
def open_spider(self,spider):
print('爬虫开始了 ...')
def process_item(self, item, spider):
item_json = json.dumps(dict(item),ensure_ascii=False)
self.fp.write(item_json+'\n')
return item
def close_spider(self,spider):
self.fp.close()
print('爬虫结束了 ...')
运行结果:
JsonItemExporter
from scrapy.exporters import JsonItemExporter
class QsbkPipeline:
def __init__(self):
self.fp = open("duanzi.json","wb")
self.exporter = JsonItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
self.exporter.start_exporting()
def open_spider(self,spider):
print('爬虫开始了 ...')
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.exporter.finish_exporting()
self.fp.close()
print('爬虫结束了 ...')
运行结果:
JsonLinesItemExporter
from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline:
def __init__(self):
self.fp = open("duanzi.json","wb")
self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
self.exporter.start_exporting()
def open_spider(self,spider):
print('爬虫开始了 ...')
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.fp.close()
print('爬虫结束了 ...')
运行结果:
在scrapy
中不是说不能直接定义返回字典,但是一般建议现在item
中定义好然后进行调用
在item
中分别定义author
和content
class QsbkItem(scrapy.Item):
author = scrapy.Field()
content = scrapy.Field()
在qsbk_spider
中也需要进行如下修改
DOWNLOAD_DELAY
的限制并修改为1# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1
# 定义一个基本的域名
base_domain = "https://www.qiushibaike.com"
next_url = response.xpath("//ul[@class='pagination']/li[last()]/a/@href").get()
# 进行一个简单的判断
if not next_url:
return
else:
yield scrapy.Request(self.base_domain+next_url,callback=self.parse)
import scrapy
from scrapy.http.response.html import HtmlResponse
from scrapy.selector.unified import SelectorList
# 继承scrapy.Spider类
from scrapy_demo.qsbk.qsbk.items import QsbkItem
class QsbkSpiderSpider(scrapy.Spider):
name = 'qsbk_spider'
# allowed_domains 指定域名,可以限制爬虫的范围
allowed_domains = ['qiushibaike.com']
# start_urls 开始链接 一般一个即可
start_urls = ['https://www.qiushibaike.com/text/page/1/']
base_domain = "https://www.qiushibaike.com"
def parse(self, response):
# SelectorList
duanzidivs = response.xpath("//div[@class = 'col1 old-style-col1']/div")
for duanzidiv in duanzidivs:
# Selector
author = duanzidiv.xpath(".//h2//text()").get().strip()
content = duanzidiv.xpath(".//div[@class='content']//text()").getall()
content = "".join(content).strip()
item = QsbkItem(author=author, content=content)
yield item
next_url = response.xpath("//ul[@class='pagination']/li[last()]/a/@href").get()
if not next_url:
return
else:
yield scrapy.Request(self.base_domain+next_url,callback=self.parse)
import scrapy
class QsbkItem(scrapy.Item):
author = scrapy.Field()
content = scrapy.Field()
from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline:
def __init__(self):
self.fp = open("duanzi.json","wb")
self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
self.exporter.start_exporting()
def open_spider(self,spider):
print('爬虫开始了 ...')
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.fp.close()
print('爬虫结束了 ...')
BOT_NAME = 'qsbk'
SPIDER_MODULES = ['qsbk.spiders']
NEWSPIDER_MODULE = 'qsbk.spiders'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1
# 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; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'qsbk.pipelines.QsbkPipeline': 300,
}
美好的日子总是短暂的,虽然还想继续与大家畅谈,但是本篇博文到此已经结束了,如果还嫌不够过瘾,不用担心,我们下篇见!