scrapy爬虫入门练习-python爬虫scrapy框架

311次阅读
没有评论

安装scrapy:

使用命令:pip install Scrapy

创建爬虫项目

使用命令:scrapy startproject test2

创建爬虫

使用命令:scrap genspider uyghur uyghur.people.com.cn

scrapy爬虫入门练习-python爬虫scrapy框架

编辑uyghur.py

输入如下代码:

import scrapy
import re

class UyghurSpider(scrapy.Spider):
name = ‘weiwuer’
allowed_domains = [‘uyghur.people.com.cn’]

start_urls = [f’http://uyghur.people.com.cn/155989/{page}.html’ for page in range(15825000, 15851000)
]

def parse(self, response):
if response.status != 404:
title = response.xpath(“//div[@class=’text_con_title’]/h1”).get() # + response.xpath(“//div[@class=’text_con_title’]/h5”).get()
author = response.xpath(“//div[@class=’text_con_title’]/h2/a/text()”).get()
time = response.xpath(“//div[@class=’text_con_title’]/h2/text()”).get()[:16]

content_s = response.xpath(“//div[@class=’text clearfix’]”).get()
str_first = re.sub(‘<.*?>’, “”, content_s) # 匹配所有html标签并用“”代替
content = str_first.replace(‘\r\n’, “”) # 将换行符替换成空
content = content.replace(‘\n’, “”)
#print(‘title:’,title, ‘author:’,author,’time:’,time, ‘content:’,content)
items = {

“title”:title,
“author”: author,
“time”:time,
“content”:content
}
yield items

修改setting文件:

BOT_NAME = ‘test2’

SPIDER_MODULES = [‘test2.spiders’]
NEWSPIDER_MODULE = ‘test2.spiders’

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = ‘test2 (+http://www.yourdomain.com)’

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

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; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36′

}
FEED_EXPORT_ENCODING = ‘utf-8’

运行爬虫

scrapy crawl uyghur –o weiwuer_result.json

其中后面表示输出为json文件

scrapy爬虫入门练习-python爬虫scrapy框架

json结果

scrapy爬虫入门练习-python爬虫scrapy框架

注意:

1.Scrapy官方可查文档或者​http://www.scrapyd.cn/doc”>​​http://www.scrapyd.cn/doc​​​。主要在于网站审查元素和匹配内容。

2.对于本文匹配方式主要使用的是xpath,可以使用xpath helper进行辅助匹配。

Xpath helper 插件自行百度

Xpath使用主要在于//开始,后面接标签,接着可使用/进一步匹配。

另外@后跟属性值,如//div[@class=’text clearfix’],匹配class=’text clearfix’属性值为等号后的内容。还可以//div/a/@href 进行匹配a中的href后的内容,即网址。

3.最后用到正则过滤正文内容

如去掉html标签:

            str_first = re.sub(‘<.*?>’, “”, content_s) 

去掉换行符:

            content = str_first.replace(‘\r\n’, “”)  

不足

1由于对scrapy不够熟悉,导致使用时不能完全发挥其功能,好像直接在使用request一样

2爬虫在该网站的一些其他页面效果不够好,因为网站的架构早期有些差别,不能够统一格式进行匹配。如下图,同样的发布时间,其格式却有巨大差异。

scrapy爬虫入门练习-python爬虫scrapy框架

scrapy爬虫入门练习-python爬虫scrapy框架

   3 另外,速度过慢,同样因为上述原因,尽管可以找到很多有效的网址,如​http://uyghur.people.com.cn/155988/309877/index1.html%EF%BC%8C%E5%AF%B9%E6%9C%AB%E5%B0%BE%E7%9A%841%E8%BF%9B%E8%A1%8C0-100″>​http://uyghur.people.com.cn/155988/309877/index1.html,对末尾的1进行0-100​​替换,但是里面的新闻网站架构差异过大,我才用的是如下方式进行暴力寻找网址,这些范围内的新闻html格式较为统一,便于抓取。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-11-01发表,共计2396字。
新手QQ群:570568346,欢迎进群讨论 Python51学习