python3 多线程 采集 xpath
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''Thread3 多线程测试采集'''
import threading,time,queue,Mongo_utils,mysqlUtils,requests,json,os
from lxml import html
etree = html.etree
exitFlag = 0
db = Mongo_utils.mongodb_15_27017task()
table = db["xx_anjuke_agent1"]
table_urls = db["xx_spider_urls1"]
list_pro = mysqlUtils.select_pro()
list_urls = table_urls.find().limit(2000)
insert_list = []
del_list = []
class myThread(threading.Thread):
def __init__(self,threadId,name,q):
threading.Thread.__init__(self)
self.threadId = threadId
self.name = name
self.q = q def run(self):
print("开始线程" + self.name)
spider(self.name,self.q)
print("退出线程" + self.name)
def head():
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"cache-control": "max-age=0",
"upgrade-insecure-requests": "",
"Connection": "keep-alive",
"Content-Type": "text/html; charset=UTF-8",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
}
return headers
def spider(name,q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
i = q.get()
queueLock.release()
_id = i["_id"]
city = i["city"]
zone = i["zone"]
street = i["street"]
urls = i["urls"]
headers = head()
try:
url = "https://。。。。。。。。。。。" % _id
# //,proxies=proxy
response_contact = requests.session().get(url=url, allow_redirects=False, headers=headers,
timeout=1)
print(response_contact.status_code)
if response_contact.status_code == 302:
print("验证")
print(url)
os._exit(0)
res = json.loads(response_contact.text) contact = res['data']
response_dl = requests.session().get(url=urls, allow_redirects=False, headers=headers,
timeout=1)
if response_dl.status_code == 302:
print("验证")
print(urls)
os._exit(0)
if ("获取成功") not in response_contact.text or ("房屋编码") not in response_dl.text:
print("pass")
pass
html = etree.HTML(response_dl.content)
name = html.xpath("//div[@class='brokercard-name']/text()")[0].strip()
company = html.xpath("//div[@class='broker-company']/p[1]/a/text()")[0]
company_url = html.xpath("//div[@class='broker-company']/p[1]/a/@href")[0]
store = html.xpath("//div[@class='broker-company']/p[2]/span/text()")[0]
# re = name, company, company_url, store, contact,_id,city,zone,street
staffNo = "https://anjuxingye1.anjuke.com/gongsi-jjr-%s/" % _id
mydict = {"_id": _id, "city": city, "zone": zone, "street": street, "name": name, "company": company,
"company_url": company_url,
"store": store, "site": "anjuke", "store_url": "", "staffNo": "", "store_url": "",
"staffNo": staffNo, "tag": "", "all_comm": ""
, "contact": contact} insert_list.append(mydict)
# del_list.append(urls)
print("size: %s" % insert_list.__len__())
except:
pass
print("%s processing %s" % (name, i))
else:
queueLock.release()
# time.sleep(1) threadList = range(0,5)
queueLock = threading.Lock()
workQueue = queue.Queue(50000)
threads = []
threadID = 1
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1 # 填充队列
queueLock.acquire()
for word in list_urls:
workQueue.put(word)
queueLock.release() # 等待队列清空
while not workQueue.empty():
pass
if insert_list.__len__() > 10:
try:
table.insert_many(insert_list, ordered=False)
# table_urls.remove({"urls": {"$in": del_list}})
print("插入1000")
except Exception as e:
print(e)
insert_list.clear()
del_list.clear()
# 通知线程是时候退出
# os._exit(0)
exitFlag = 1
try:
table.insert_many(insert_list, ordered=False)
# table_urls.remove({"urls": {"$in": del_list}})
print("插入1000")
except:
pass
insert_list.clear()
del_list.clear()
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
python3 多线程 采集 xpath的更多相关文章
- Python3做采集
出于某些目的,需要在网上爬一些数据.考虑到Python有各种各样的库,以前想试试Pycharm这个IDE,就决定用它了.首先翻完<深入Python3>这本书,了解了它的语法之类的.下面就开 ...
- python3 多线程爬虫模板
原文:https://www.jianshu.com/p/06ae2373f560 1 import threading # 多线程模块 2 import queue # 队列模块 3 import ...
- 【Python数据分析】Python3多线程并发网络爬虫-以豆瓣图书Top250为例
基于上两篇文章的工作 [Python数据分析]Python3操作Excel-以豆瓣图书Top250为例 [Python数据分析]Python3操作Excel(二) 一些问题的解决与优化 已经正确地实现 ...
- python3多线程趣味详解
python3的多线程很多人无法理解是怎么运行的,因此本文从程序猿的日常生活出发,写了一个由浅入深的多线程教程,这样子大家就不会觉得陌生了,多线程真的很简单很简单! 不要讲多线程局限于库或者框架,自己 ...
- Python3 多线程的两种实现方式
最近学习 Python3 ,希望能掌握多线程的使用,在此做个笔记.同时也希望Python 牛人指点错误.关于线程的概念,前面简单总结了一下 java 的多线程,传送门:java 多线程概念,三种创建多 ...
- python3 多线程获取数据实例
import requestsimport jsonfrom retrying import retryfrom lxml import etreefrom queue import Queueimp ...
- Python3 多线程
多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进 ...
- python3 多线程编程
python / 并发 / 线程 / 对象 / 编程 0.什么是线程 1. 多线程模块 2. 创建线程的方法 3. join()方法 4.isAlive()方法 5. name属性和daemon属 ...
- Python多线程采集百度相关搜索关键词
百度相关搜索关键词抓取,读取txt关键词,导出txt关键词 #百度相关搜索关键词抓取,读取txt关键词,导出txt关键词 # -*- coding=utf-8 -*- import request ...
随机推荐
- Unix/Linux下如何查看DNS服务器地址
使用命令: cat /etc/resolv.conf 或者 less /etc/resolv.conf 即可. 详细请见:http://www.cyberciti.biz/faq/how-to-fin ...
- Maven setting.xml简易配置
使用国内阿里云的下载源: <?xml version="1.0" encoding="UTF-8"?> <settings> <l ...
- 14Flutter StatefulWidget有状态组件、页面上绑定数据、改变页面数据、实现计数器功能、动态列表
/** * Flutter StatefulWidget有状态组件.页面上绑定数据.改变页面数据 * 在Flutter中自定义组件其实就是一个类,这个类需要继承StatelessWidget/Stat ...
- logback 和 log4j对比,及相关配置
Logback 一.logback的介绍 Logback是由log4j创始人设计的又一个开源日志组件.logback当前分成三个模块:logback-core,logback- classic和log ...
- 使用Python处理Excel表格的简单方法
使用Python处理Excel表格的简单方法 这篇文章主要介绍了使用Python处理Excel表格的简单方法,本文给大家介绍的非常详细,需要的朋友可以参考下 Excel 中的每一个单元,都会有这些属性 ...
- 读写Session
读写Session Session是保存在服务端的字典 Session与Cookie有些类似,都是通过字典管理key-value对,只不过Cookie是保存在客户端的字典,而Session是保存在服务 ...
- Hadoop 部署之 Hadoop (三)
目录 一.Hadoop 介绍 1.HDFS 介绍 2.HDFS 组成 3.MapReduce 介绍 4.MapReduce 架构 JobTracker TaskTracker 二.Hadoop的安装 ...
- mac Access denied for user 'root'@'localhost' (using password: YES)
1:苹果->系统偏好设置->最下边点mysql 在弹出页面中 关闭mysql服务 2: Start it in safe mode 进入终端 输入: cd /usr/local/mysql ...
- 【OpenCV开发】使用OpenCV的OpenCL(ocl)模块
参加OpenCV的OpenCL模块(以下称OCL)移植工作已经有2个月了.这里我说移植而不是开发,是因为大部分OCL模块的函数都是从已经很成熟的GPU模块移植过来的.于是目前阶段OCL模块所支持的函数 ...
- 【并行计算与CUDA开发】英伟达硬件加速编解码
硬件加速 并行计算 OpenCL OpenCL API VS SDK 英伟达硬件编解码方案 基于 OpenCL 的 API 自己写一个编解码器 使用 SDK 中的编解码接口 使用编码器对于 OpenC ...