1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python多线程队列爬虫流程图_python 多线程爬虫 队列queue问题。

python多线程队列爬虫流程图_python 多线程爬虫 队列queue问题。

时间:2019-02-13 09:43:18

相关推荐

python多线程队列爬虫流程图_python 多线程爬虫 队列queue问题。

思路是 先构造url列表 all_url

然后

for i in range(0, len(all_url)):

urlqueue.put(all_url[i])

然后get 做到每次从列表中取出url

现在问题是,range后面 无法写成 0到列表长度

会显示IndexError: list index out of range

意思是 索引错误:列表索引超出范围

而且列表是没有任何问题的,没有空

而且如果列表长度是2000, 那么只能range(0, 1000),这样就无任何报错

这样就很麻烦

下面是代码

import requests

from lxml import html

import time

import threading

from queue import Queue

class Spider(threading.Thread):

def __init__(self, name, urlqueue):

super().__init__()

self.name = name

self.urlqueue = urlqueue

def run(self):

headers = {

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36'

}

print('线程 :' + self.name + '启动')

while not self.urlqueue.empty():

try:

url = self.urlqueue.get()

rep = requests.get(url, headers = headers, timeout = 5)

time.sleep(1)

if rep.status_code == 200:

print("链接成功")

self.parse(rep)

print(url + " 爬取完成")

except Exception as e:

print("主页::" +url + " 链接失败, 原因::", e)

pass

print('线程 :' + self.name + '结束')

def parse(self, rep):

con = rep.content

sel = html.fromstring(con)

title = sel.xpath('//div[@class="titmain"]/h1/text()')

title = str(title).replace(']', '').replace('[', '').replace("'", '').replace(",", '').replace(r"\r\n", "").replace('"', '').replace(' ', '').replace(r'\xa0', '').replace('?', '').replace('/', '').replace(r'\u3000', ' ')

date = sel.xpath('//div[@class="texttit_m1"]/p/text()')

date = str(date).replace(']', '').replace('[', '').replace("'", '').replace(r'\u3000', ' ')

if len(date) > 20:

file_name = title + ".txt"

a = open(file_name, "w+", encoding='utf-8')

a.write('\n' + str(title) + '\n' + '\n' + str(date))

print(file_name + '保存成功')

a.close

else:

pass

if name == '__main__':

with open('未爬取url.txt') as f:

data = f.readline()

#读取数据行

james = data.strip().split(',')

#将数据转换为列表

all_url = []

for jame in james:

a=eval(jame)

#去除ifu两端引号

all_url.append(a)

print(len(all_url))

start = time.time()

urlqueue = Queue()

threadNum = 3 #线程数量

for i in range(0, 1468):

urlqueue.put(all_url[i]) #问题在这里

del all_url[i]

threads = []

for i in range(1, threadNum+1):

thread = Spider("线程" + str(i), urlqueue)

thread.start()

threads.append(thread)

for thread in threads:

thread.join()

with open('未爬取url.txt', 'w+') as b:

b.write('\n'.join([str(all_url)]))

b.write('\n' + '=' *50 + '\n')

b.close

print(' 未爬取url 保存完成')

end = time.time()

print("-------------------------------")

print("下载完成. 用时{}秒".format(end-start))

另外 url是从txt读的 不知道怎么传上来, 最后构造的all_url列表是肯定没有问题的

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。