我想从以下网站www.miastoksiazek.net抓取所有博客文章。主要目标是递归地遵循所有可用的URL,抓取段落,将其添加到数据库(可以保存到文本文件或其他内容)。我只想拥有段落语料库,所以不需要将它们分组,即来自同一博客文章。问题在于这些博客文章在HTML代码中的书写方式不同(至少其中一些),而且我在抓取网站方面没有特别深的经验。而且,我有一种感觉,并不是所有博客文章都被抓取了,或者某些链接没有得到应有的关注。由于我是初学者,因此我使用scrapy
而不是beautiful soup
。这是我到目前为止所得到的
books_spider.py
import scrapy
from scrapy import Request
from scrapy.linkextractors import LinkExtractor
from ..items import LangCorpusItem
class BooksWorldSpider(scrapy.Spider):
name = "books"
allowed_domains = ["miastoksiazek.net"]
start_urls = ["http://miastoksiazek.net/"]
all_links_extractor = LinkExtractor(allow_domains="miastoksiazek.net",
deny_domains=("youtube.com", "twitter.com", "facebook.com", "pinterest.com",
"google.com", "blogspot.com", "pl.wikipedia.org"))
target_links_extractor = LinkExtractor(allow_domains="miastoksiazek.net",
deny_domains=("youtube.com", "twitter.com", "facebook.com", "pinterest.com",
"google.com", "blogspot.com", "pl.wikipedia.org"),
restrict_css=(".item-content h2", ".post-entry"))
def parse(self, response):
target_links = self.target_links_extractor.extract_links(response)
if target_links:
for l in target_links:
yield Request(l.url, callback=self.parse_item)
links = self.all_links_extractor.extract_links(response)
if links:
for l in links:
yield Request(l.url, callback=self.parse)
def parse_item(self, response):
items = LangCorpusItem()
for entry in response.xpath('//div[@class = "post-entry"]/p/text()'):
for paragraph in entry.xpath(".//p/text()").extract():
if paragraph and paragraph.strip() and "Copyright" not in paragraph:
items["text"] = paragraph
items["link"] = response.url
yield items
pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
class LangCorpusPipeline(object):
def __init__(self):
self.conn = pymongo.MongoClient(
host="localhost",
port=27017
)
db = self.conn["miasto_ksiazek"]
self.collection = db["text_table"]
def process_item(self, item, spider):
self.collection.insert(dict(item))
return item
items.py
import scrapy
class LangCorpusItem(scrapy.Item):
# define the fields for your item here like:
text = scrapy.Field()
link = scrapy.Field()
settings.py
# -*- coding: utf-8 -*-
# Scrapy settings for lang_corpus project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'lang_corpus'
SPIDER_MODULES = ['lang_corpus.spiders']
NEWSPIDER_MODULE = 'lang_corpus.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'lang_corpus (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 10
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# 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',
#}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'lang_corpus.middlewares.LangCorpusSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'lang_corpus.middlewares.LangCorpusDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'lang_corpus.pipelines.LangCorpusPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'