#!/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的更多相关文章

  1. Python3做采集

    出于某些目的,需要在网上爬一些数据.考虑到Python有各种各样的库,以前想试试Pycharm这个IDE,就决定用它了.首先翻完<深入Python3>这本书,了解了它的语法之类的.下面就开 ...

  2. python3 多线程爬虫模板

    原文:https://www.jianshu.com/p/06ae2373f560 1 import threading # 多线程模块 2 import queue # 队列模块 3 import ...

  3. 【Python数据分析】Python3多线程并发网络爬虫-以豆瓣图书Top250为例

    基于上两篇文章的工作 [Python数据分析]Python3操作Excel-以豆瓣图书Top250为例 [Python数据分析]Python3操作Excel(二) 一些问题的解决与优化 已经正确地实现 ...

  4. python3多线程趣味详解

    python3的多线程很多人无法理解是怎么运行的,因此本文从程序猿的日常生活出发,写了一个由浅入深的多线程教程,这样子大家就不会觉得陌生了,多线程真的很简单很简单! 不要讲多线程局限于库或者框架,自己 ...

  5. Python3 多线程的两种实现方式

    最近学习 Python3 ,希望能掌握多线程的使用,在此做个笔记.同时也希望Python 牛人指点错误.关于线程的概念,前面简单总结了一下 java 的多线程,传送门:java 多线程概念,三种创建多 ...

  6. python3 多线程获取数据实例

    import requestsimport jsonfrom retrying import retryfrom lxml import etreefrom queue import Queueimp ...

  7. Python3 多线程

    多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进 ...

  8. python3 多线程编程

    python / 并发 / 线程 / 对象 / 编程   0.什么是线程 1. 多线程模块 2. 创建线程的方法 3. join()方法 4.isAlive()方法 5. name属性和daemon属 ...

  9. Python多线程采集百度相关搜索关键词

    百度相关搜索关键词抓取,读取txt关键词,导出txt关键词 #百度相关搜索关键词抓取,读取txt关键词,导出txt关键词   # -*- coding=utf-8 -*- import request ...

随机推荐

  1. c++ template Queue

    #pragma once#include <iostream>#include <iomanip> using namespace std; template<class ...

  2. Spring事务管理2----编程式事务管理

    编程式事务管理 通过使用将Spring框架提供的TransactionTemplate模板注入到业务层来进行事务管理,这样对业务层原来的代码修改过多.不利于项目的后期维护. 以下是声明式事务管理的具体 ...

  3. 神经网络(NN)实现多分类-----Keras实现

    IRIS数据集介绍   IRIS数据集(鸢尾花数据集),是一个经典的机器学习数据集,适合作为多分类问题的测试数据,它的下载地址为:http://archive.ics.uci.edu/ml/machi ...

  4. 开发工具之GIT

    GIT WORKFLOW this readme created on 2019.07.28 by Suarez7988 这是一遍介绍git版本控制流程的中文说明,必须通篇阅读一下 https://g ...

  5. 35.百度云语音识别接口使用及PyAudio语音识别模块安装

    百度云语音识别接口使用: 百度云语音识别接口文档:https://cloud.baidu.com/doc/SPEECH/ASR-API.html#JSON.E6.96.B9.E5.BC.8F.E4.B ...

  6. 幻数浅析(Magic Number)

    在源代码编写中,有这么一种情况:编码者在写源代码的时候,使用了一个数字,比如0x2123,0.021f等,他当时是明白这个数字的意思的,但是别的程序员看他的代码,可能很难理解,甚至,过了一段时间,代码 ...

  7. mac必装软件

    1.IINA: https://iina.io/ 2.keka: https://www.keka.io/zh-cn/ 3.欧陆词典: https://www.eudic.net/v4/en/app/ ...

  8. [百家号]7nm ARM 64核!华为Hi1620高性能CPU公开:3.0GHz

    7nm ARM 64核!华为Hi1620高性能CPU公开:3.0GHz https://baijiahao.baidu.com/s?id=1617735663824201180&wfr=spi ...

  9. 处理vue页面406问题纪要

    1.servlet-mapping url-pattern / 与 /* 的区别注意关注 2.mvc:resource 是否生效,注意关注,如不生效,可在 web.xml中配置<servlet- ...

  10. SQL SERVER DAY函数

    定义: DAY函数返回指定日期的日的部分 语法: DAY(date) 参数: ①date参数是合法的日期表达式. 返回值: int型数据 例:  声明:本文是本人查阅网上及书籍等各种资料,再加上自己的 ...