python爬虫–scrapy(初识)
scrapy环境安装
因为我是同时安装anaconda和python3.7,所以在使用pip的时候总是会显示anaconda中已经安装(众所周知),就很烦 。一气之下,挂着VPN并且在CMD中使用conda install scrapy
,然后安装好。
PS:也有可能直接使用conda install scrapy就可以了(我没试)
最近又在试发现直接cd到python目录下,并且我已经安装python3.8,更新pip,然后pip install scrapy就成功了。没有冲突一说。
出现下面这张图后,就说明已经安装完成
scrapy基本使用
使用命令行创建scrapy项目工程scrapy startproject qiushi
就会提示你创建成功
然后提示你cd到该目录下,并且创建first spider
命令scrapy genspider example example
配置文件的修改
别忘了user-Agent
运行项目文件
#终端输入
scrapy crawl first
糗事百科数据解析
import scrapy
class QiubaiSpider(scrapy.Spider):
name = 'qiubai'
#allowed_domains = ['www.xxx.com']
start_urls = ['https://www.qiushibaike.com/text/']
def parse(self, response):
div_list = response.xpath('//*[@id="content"]/div/div[2]/div')
for div in div_list:
#xpath返回的是列表,但是列表元素一定是Selector类型的对象
#extract可以将Selector对象中的data参数存储的字符串提取出来
#author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
#.extract_first()是确定列表中只存在一个元素
author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()