python=3.9
itemadapter=0.8.0
mysql_connector_repackaged=0.3.1
Scrapy=2.9.0
在pycahrm中的terminal或者在windows下的cmd中创建scrapy项目:
scrapy startproject projectname
创建一个爬虫并指定爬取网站
scrapy genspider spidername targetWebsite
运行这条指令后,会在spider文件中多一个quotes.py
目录结构:
projectname/
│
├── news/
│ ├── init.py
│ ├── items.py #定义了爬取的数据结构
│ ├── middlewares.py #定义爬取时的中间件
│ ├── pipelines.py # 定义数据管道
│ ├── setting.py #全局配置文件
│ └── spiders/ #里面包含一个个spider的实现,每个spider都对应一个python文件
│ ├── init.py
│ └── spidername.py
│
└── scrapy.sfg #项目配置文件
创建item:
import scrapy
class ScrapytutorialItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()
css解析页面:
item['text'] = quote.css('.text::text').extract_first()
item['author'] = quote.css('.author::text').extract_first()
item['tags'] = quote.css('.tags .tag::text').extract()
::text 选择需要的正文数据
::attr(属性名) 选择需要的属性
保存到数据库:
class MySQLPipeline:
def __init__(self):
self.connection = mysql.connector.connect(
host=config.HOST,
user=config.USER,
passwd=config.PASSWORD,
database=config.DB
)
self.cursor = self.connection.cursor()
def process_item(self, item, spider):
tags = ''.join(x for x in item['tags'])
self.cursor.execute("INSERT INTO mivoetable (text, author, tags) VALUES (%s, %s, %s)", (item['text'], item['author'], tags))
self.connection.commit()
return item
def close_spider(self, spider):
self.cursor.close()
self.connection.close()
1.笔者踩了个大坑:pymysql在scrapy框架下无法运行代码,只能用mysql_connector_repackaged来存到mysql数据库
2.在执行这句话(excute函数中是两部分,第一部分是sql语句,第二部分是一个由元组组成的数据):self.cursor.execute(“INSERT INTO mivoetable (text, author, tags) VALUES (%s, %s, %s)”, (item[‘text’], item[‘author’], tags))
3.callback机制:方法运行完后,response返回的参数依然传到该函数,parse就是callback机制