截止到目前为止,我运行就不知道在干嘛,等半天没啥响应
相关代码:
#用于request发送请求
import requests
#建立队列
from multiprocessing import Queue
#用正则表达式来抽取网页数据
import re
#采用多线程爬取
import threading
class Crawl_page(threading.Thread):
#用于给页码发送请求
def __init__(self, thread_name, page_queue, data_queue):
super(Crawl_page,self).__init__()
#线程名称
self.thread_name = thread_name
self.page_queue = page_queue
self.data_queue = data_queue
self.header = {
"Host": "jobs.51job.com",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
"Sec-Fetch-Dest": "document",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site": "none",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-User": "?1",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9"
}
def run(self):
#多线程的启动方法
print("当前启动的线程为{}".format(self.thread_name))
#使用no_wait就相当于将timeout设置为无限小,当队列堵塞get不出来东西就会直接抛异常
#当page_flag 为True的时候,终止对page_queue的get
while not page_flag:
try:
page = self.page_queue.get_nowait()
except Exception as e:
pass
else:
# 因为不同页面网页只会变化同一个url中的某一处的数字,可以用page的值去格式化每一次的page_url
page_url = "https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,{}.html".format(page)
print("当前请求的URL为:{}".format(page_url))
#对当前页面的url发送get请求,并将获取的数据转码
response = requests.get(url=page_url, headers=self.header)
response.encoding = "gbk"
#将转码后的数据放入data_queue中
self.data_queue.put(response.text)
class Crawl_html(threading.Thread):
#用于处理页码返回数据
pass
page_flag = False
data_flag = False
def main():
#页码队列
page_queue = Queue()
#网页数据队列
data_queue = Queue()
#向page_queue中存储页码
for page in range(1,915):
page_queue.put(page)
#qsize()用于获取队列长度
print("当前页码队列中储存的页码总量为{}".format(page_queue.qsize()))
crawlist = ["页码处理线程1号","页码处理线程2号","页码处理线程3号"]
#存储线程
page_thread_list = []
for thread_name_page in crawlist:
#引用Crawl_page函数,创建线程
thread_page = Crawl_page(thread_name=thread_name_page, page_queue=data_queue, data_queue=data_queue)
#启动线程
thread_page.start()
#将创建好的线程导入列表中,方便后面使用这些线程
page_thread_list.append(thread_page)
#线程的停止
global page_flag
#当page_queue不为空时,正常运行;当page_queue为空,page_flag变为True,从而让run()函数停止运行
while not page_queue.empty():
pass
page_flag = True
#释放线程
for thread_page_join in page_thread_list:
thread_page_join.join()
print(thread_page_join.thread_name,"处理结束")
if __name__ == "__main__":
main()
相关截图:

运行到这里就一直这样,然后电脑风扇在疯狂转...是我代码有问题还是我网络有问题?
12
收起
正在回答 回答被采纳积分+1
1回答
4.入门主流框架Scrapy与爬虫项目实战
- 参与学习 人
- 提交作业 107 份
- 解答问题 1672 个
Python最广为人知的应用就是爬虫了,有趣且酷的爬虫技能并没有那么遥远,本阶段带你学会利用主流Scrapy框架完成爬取招聘网站和二手车网站的项目实战。
了解课程


恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星