Python scrapy爬取带验证码的列表数据

首先所需要的环境:(我用的是Python2的,可以选择python3,具体遇到的问题自行解决,目前我这边几百万的数据量爬取)
环境:

Python 2.7.10 
Scrapy Scrapy 1.5.0
第三方库:
PyMySQL==0.8.0
Scrapy==1.5.0
pytesseract==0.2.0
pip==10.0.1
Pillow==5.1.0
logger==1.4
bs4==0.0.1
requests==2.18.4

创建项目 
scrapy startproject mytest
创建爬虫程序
cd mytest 
scrapy genspider name XXX.com

直接贴代码具体需要注意的特殊颜色标出有注释

-- coding: utf-8 --

import scrapy 
import pytesseract  #验证码识别库
from PIL import Image #验证码图片处理
from scrapy.http import Request
from yishi.items import YishiItem #items定义爬取字段
from yishi.settings import MYSQL_HOST, MYSQL_DBNAME, MYSQL_USER, MYSQL_PASSWD #settings数据库配置 
import pymysql #连接数据库
import logging #打印日志
#设置日志
log_filename = '../static/data/info.log'
logging.basicConfig(filename=log_filename, filemode='a', level=logging.INFO)  
class CreditSpider(scrapy.Spider):
	name = 'name'
	baseURL = 'https://xxx.com' 
	#start_urls = ''
	#设置headers,打开网页直接看请求headers复制进去就可以了
	headers = {
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
		'Accept-Encoding': 'gzip, deflate, br',
		'Connection': 'keep-alive',
		'Host': 'xxx',
		'Upgrade-Insecure-Requests': 1,
		'User-Agent': 'xxx',
	}
	#数据库
	connect = pymysql.connect(
		host=MYSQL_HOST,
		db=MYSQL_DBNAME,
		user=MYSQL_USER,
		passwd=MYSQL_PASSWD,
		charset='utf8',
		use_unicode=True)

	#重写start_requests
	def start_requests(self):
		return [Request(self.baseURL+'xxx',
						headers=self.headers,
						callback=self.parse,
						dont_filter=True, #scrapy会对request的URL去重(RFPDupeFilter),加上dont_filter则告诉它这个URL不参与去重
						)
				]

	#首先需要请求一次网页
	def parse(self, response):
		#每次查询1条数据,搜索列表所需要的条件
		cursor = self.connect.cursor()
		sql = 'select id,xxx,xxx,xxx from xxx where xxx order by id limit 1'
		cursor.execute(sql)
		res = cursor.fetchall()
		if res:
			#请求网站所需要的参数,搜索条件
			data = {
				"xxx": res[0][1],
				"xxx": '',
				"xxx": '',
				"xxx": res[0][2],
				"xxx": '',
				"xxx": '',
				"xxx": '',
			}
			cursor.close()
			return scrapy.Request(self.baseURL + '/xxx/captcha',  #验证码图片地址
								  headers=self.headers, 
								  meta={'data': data, 'dr_id': res[0][0], 'static': res[0][3], 'len': len(res)}, #第一次请求的参数传给下次请求,可以保存cookie之类的
								  callback=self.creditRes,
								  dont_filter=True
								  )
		else:
			#数据表中条件没有的时候结束爬虫,每次爬取要更新下条件表
			print '执行完毕!'
			pass

	#再次请求存验证码图片
	def creditRes(self, response):
			#保存验证码
			captchaFile = '../static/images/code/captcha.png'
			with open(captchaFile, 'wb') as f:
				f.write(response.body)
			try:
				#pytesseract识别验证码
				image = Image.open(captchaFile)
				captcha_value = pytesseract.image_to_string(image)
				print '验证码为:'+captcha_value
			except:
				#验证码失败 重新请求
				logging.info('验证码获取失败')
				return self.start_urls
			#识别后的验证码作为参数使用
			data = response.meta.get("data")
			data["validCode"] = captcha_value

			return [scrapy.FormRequest(
				url=self.baseURL+'xxx',  #带上全部参数再次请求取数据
				formdata=data,
				method='GET',
				meta={'dr_id': response.meta.get("dr_id"), 'static': response.meta.get("static"), 'len': response.meta.get("len"),
					  'captcha_value': captcha_value}, #带上部分参数保存或更新状态用
				headers=self.headers,
				callback=self.creditdata,
				dont_filter=True,
			)]

	def creditdata(self, response):
		#获取验证码错误内容,识别验证是否成功
		code_data = response.xpath("//span[@class='error']")
		if code_data:
			code = code_data.xpath(".//text()").extract()[0].decode('UTF-8')
			logging.info('验证码校验失败,验证码:'+str(response.meta.get("captcha_value")))
		else:
			code = ''
		#验证码错误时不更新状态,继续重复爬取
		dr_id = response.meta.get("dr_id")
		#不存在验证码识别更新状态,插入数据
		if code.strip() not in ('验证码错误', '验证码不能为空'):
			cursor = self.connect.cursor()
			sql = 'update xxx set status=%s where id=%s' % (1, dr_id)
			cursor.execute(sql)
			self.connect.commit()
			cursor.close()
		else:
			#验证码失败不更新状态
			logging.info('验证码错误')

		node_list = response.xpath("//table[@id='formresult']/tbody/tr")
		# 更新状态 0还未抓取数据 1已经抓取
		logging.info('当前执行条件表id为'+ str(dr_id))
		if node_list:
			for node in node_list:
				item = YishiItem()
				item['xxx'] = dr_id
				item['xxx'] = node.xpath(".//td[1]/text()").extract()[0].decode('UTF-8')
				item['xxx'] = node.xpath(".//td[2]/text()").extract()[0].decode('UTF-8')
				item['xxx'] = node.xpath(".//td[3]/text()").extract()[0].decode('UTF-8')
				item['xxx'] = node.xpath(".//td[4]/text()").extract()[0].decode('UTF-8')
				item['xxx'] = node.xpath(".//td[5]/text()").extract()[0].decode('UTF-8')
				item['xxx'] = node.xpath(".//td[6]/text()").extract()[0].decode('UTF-8')
				item['xxx'] = node.xpath(".//td[7]/text()").extract()[0].decode('UTF-8')
				yield item
		#分页数据,根据下一页爬取,可获取下页按钮状态去爬取分页数据
		nextPage = response.xpath("//a[@class='disable' and @class='next']")
		if nextPage:
			if not len(nextPage):
				#下一页a标签url
				url = response.xpath("//a[@class='disable' and @class='next']/@href").extract()[0]
				yield scrapy.Request(self.baseURL+'/'+url, callback=self.creditdata)

		# 根据状态status=0判断是否继续爬取数据
		len = response.meta.get("len")
		if not len == 0:
			yield scrapy.Request(self.baseURL+'xxx',
								 headers=self.headers,
								 callback=self.parse,
								 dont_filter=True)


items设置:
	xxx = scrapy.Field()
	xxx = scrapy.Field()
...

pipelines存数据库这个就不说了根据自己的业务
注:目前我网站验证码比较简单可以直接使用pytesseract,识别率95%以上,也可以用别的方式CNN等方式识别
个人感觉用 requests.get() 方式写要简单一些,本地已测试过,根据业务需求用scrapy完成的。
requests.get() 主要问题就是 session = requests.session() 这句是重点

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Scrapy框架和Selenium模拟登陆微博是一种常见的爬取微博评论的方法。通过Scrapy框架可以方便地发送HTTP请求和解析响应数据,而Selenium则可以模拟用户登录微博。 然而,微博对于爬虫的反爬措施比较严格,因此在爬取过程中可能会遇到一些问题。微博会自动跳转到评论比较少的页面,导致爬取的评论数量不多。此外,微博还会检测到爬虫程序并采取一些措施来防止爬取。 为了应对网站的反爬策略,可以采取以下措施: 1. 使用代理IP:通过使用代理IP可以隐藏真实的请求来源,增加爬虫的隐匿性。 2. 随机延时:在发送请求之前,可以引入随机延时,模拟人类的操作习惯,以避免被检测为爬虫。 3. 设置请求头:设置合理的请求头信息,包括User-Agent、Referer等,使请求看起来更像是正常的浏览器请求。 4. 使用验证码识别:如果网站有验证码机制,可以使用验证码识别技术自动处理验证码。 5. 使用分布式爬虫:通过使用分布式爬虫,可以通过多个节点来爬取数据,减少单个节点的访问频率,降低被封禁的风险。 综上所述,使用Scrapy框架和Selenium模拟登陆微博可以实现爬取微博评论的功能,但同时也需要应对微博的反爬措施,采取相应的策略来提高爬取的成功率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [python爬虫——scrapy+selenium爬取新浪微博及评论](https://blog.csdn.net/csdn950212/article/details/86583624)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值