python爬虫scrapy知乎案例
时间: 2023-09-18 11:07:11 浏览: 206
以下是一个简单的scrapy爬取知乎热门话题的案例:
首先,需要安装scrapy和其他需要的库:
```
pip install scrapy
pip install requests
pip install scrapy-splash
```
然后,创建一个新的scrapy项目:
```
scrapy startproject zhihu
cd zhihu
```
接着,在`settings.py`中添加一些配置:
```python
BOT_NAME = 'zhihu'
SPIDER_MODULES = ['zhihu.spiders']
NEWSPIDER_MODULE = 'zhihu.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 3
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
SPLASH_URL = 'http://localhost:8050'
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
```
在这里,我们使用了Splash来渲染网页,因此需要添加一些相关的配置。`DOWNLOAD_DELAY`是下载延迟时间,为了避免被网站封禁,最好设置一个较长的时间。
接下来,创建一个名为`zhihu_spider.py`的Spider类:
```python
import scrapy
from scrapy_splash import SplashRequest
class ZhihuSpider(scrapy.Spider):
name = 'zhihu'
allowed_domains = ['www.zhihu.com']
start_urls = ['https://www.zhihu.com/hot']
script = '''
function main(splash, args)
assert(splash:go(args.url))
assert(splash:wait(2))
return splash:html()
end
'''
def start_requests(self):
for url in self.start_urls:
yield SplashRequest(url, self.parse, endpoint='execute', args={
'lua_source': self.script
})
def parse(self, response):
for item in response.css('.HotItem'):
yield {
'title': item.css('.HotItem-title a::text').get(),
'link': item.css('.HotItem-title a::attr(href)').get(),
}
```
在这里,我们使用了SplashRequest来请求页面,并使用Lua脚本来等待页面加载完毕。然后,我们使用CSS选择器来提取热门话题的标题和链接,并将它们存储在字典中,然后使用yield返回。
最后,运行爬虫:
```
scrapy crawl zhihu -o zhihu.csv
```
这将抓取知乎热门话题的标题和链接,并将它们存储在CSV文件中。
阅读全文