-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscraping_threads.py
193 lines (161 loc) · 5.44 KB
/
scraping_threads.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#-*- coding:utf-8 -*-
'''多线程爬取数据插入到Mysql中final_data表
ThreadUrl类读入Queue中的数据,形成表单post请求到网站,将抓取的数据写入out_queue
DatamineThread类读入out_queue中的数据,数据清理,写入数据库
'''
import requests
import cookielib
import json
import random
import csv
import datetime
import Queue
import threading
import pymysql
from bs4 import BeautifulSoup
from time import sleep
# login and save cookies
url='https://www.hoau.net/how/bse/showPriceTime.action'
url_query='https://www.hoau.net/how/bse/queryPriceTime.action'
requests = requests.Session()
requests.cookies = cookielib.LWPCookieJar('cookies')
try:
requests.cookies.load(ignore_discard=True)
except:
pass
headers = {
'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36",
'Host': "www.hoau.net",
'Pragma': "no-cache",
'Referer': "https://www.hoau.net/how/bse/showPriceTime.action",
'X-Requested-With': "XMLHttpRequest"
}
requests.get(url,headers=headers)
requests.cookies.save()
# POST form_data to site and get the data we want
def get_price(conCity,conCounty,shipperCity,shipperCounty):
form_data={'priceQueryVo.conCity':conCity,'priceQueryVo.conCounty':conCounty,
'priceQueryVo.shipperCity':shipperCity,'priceQueryVo.shipperCounty':shipperCounty}
#print form_data
r=requests.post(url_query,headers=headers,data=form_data)
a=json.loads(r.text)
shipperCity=a['priceQueryVo']['shipperCity']
shipperCounty=a['priceQueryVo']['shipperCounty']
conCity=a['priceQueryVo']['conCity']
conCounty=a['priceQueryVo']['conCounty']
price=a['priceTimeVos']
for x in price:
if x['transportType']=='ONTIME':
startPrice=x['startPrice']
heavyPrice=x['heavyPrice']
lightPrice=x['lightPrice']
deliveryTime=x['deliveryTime']#char
#print conCity,shipperCity,startPrice,heavyPrice,lightPrice
return (conCity,conCounty,shipperCity,shipperCounty,deliveryTime,startPrice,heavyPrice,lightPrice)
queue = Queue.Queue()
out_queue = Queue.Queue()
#generate queue from db : return a list
def gen_queue(num1,num2):
#conn = pymysql.connect(host='127.0.0.1',user='root', passwd='123456', db='mysql', charset='utf8')
#cur = conn.cursor()
#cur.execute("USE scrapy")
cur.execute("select fromcity,fromcountry,tocity,tocountry from cc where id>=%s and id<%s",(num1,num2))
cc_list=cur.fetchall() # tuple()
#cur.close()
#conn.close()
return cc_list
# get queue, deal, put out_queue
class ThreadUrl(threading.Thread):
def __init__(self, queue, out_queue):
threading.Thread.__init__(self)
self.queue = queue
self.out_queue = out_queue
def run(self):
i=0
while True:
i+=1
if(i%50==0):
_id=threading.current_thread().getName()
print "the thread:",_id,"scraping another 50 times!",i
sleep(random.uniform(1,1.5))
try:
cc = self.queue.get()
data=get_price(*cc) #data=(u'\u5317\u4eac\u5e02', u'\u4e1c\u57ce\u533a', u'\u5317\u4eac\u5e02', u'\u4e1c\u57ce\u533a', 15.0, 0.6, 132.0)
self.out_queue.put(data)
except Exception, e:
#print "ThreadUrl get_price() error!"
#print "%s"%(str(e))
pass
self.queue.task_done()
# get out_queue, deal
class DatamineThread(threading.Thread):
def __init__(self, out_queue):
threading.Thread.__init__(self)
self.out_queue = out_queue
def run(self):
i=0
begin=datetime.datetime.now()
conn = pymysql.connect(host='127.0.0.1',user='root', passwd='123456', db='mysql', charset='utf8')
conn.ping(True)
cur = conn.cursor()
cur.execute("USE scrapy")
while True:
i+=1
chunk = self.out_queue.get()
#self.out_queue.task_done()
###get the final data then load into db #####def func():
sqli="insert into final_data(fromcity,fromcountry,tocity,tocountry,deliveryTime,min_price,heavy_good,light_good) values(%s,%s,%s,%s,%s,%s,%s,%s)"
try:
cur.execute(sqli,(chunk[0].encode('utf-8'),chunk[1].encode('utf-8'),chunk[2].encode('utf-8'),chunk[3].encode('utf-8'),chunk[4].encode('utf-8'),chunk[5],chunk[6],chunk[7]))
cur.execute("commit")
except Exception, e:
print "DatamineThread insert error!"
#print "%s"%(str(e))
#print chunk
#check if lost connection to Mysql
if(i%50==0):
_id=threading.current_thread().getName()
print 'mysql threads:',_id,'already insert ',i,' times!'
try:
cur.execute("select 1 from final_data")
a=cur.fetchone()
check=a[0]
if(check==1):
print _id,'db insert threads connected ok!'
except:
print _id,"seems lost connection to MySQL!"
conn = pymysql.connect(host='127.0.0.1',user='root', passwd='123456', db='mysql', charset='utf8')
conn.ping(True)
cur = conn.cursor()
cur.execute("USE scrapy")
self.out_queue.task_done()
def goscrapy():
for i in range(10):
t=ThreadUrl(queue,out_queue)
t.setDaemon(True)
t.start()
for i in range(10):
dt = DatamineThread(out_queue)
dt.setDaemon(True)
dt.start()
cc_list=gen_queue(37450,1000000)#12054784=6054784+6000000 #1w
for cc in cc_list:
queue.put(cc)
print "queue is ready!"
#wait until processing finish
queue.join()
out_queue.join()
## main
def main():
begin=datetime.datetime.now()
conn = pymysql.connect(host='127.0.0.1',user='root', passwd='123456', db='mysql', charset='utf8')
#conn.ping(True)
cur = conn.cursor()
cur.execute("USE scrapy")
goscrapy()
end=datetime.datetime.now()
print 'Total times used:',(end-begin)
cur.close()
conn.close()
if __name__ == "__main__":
main()