python 采集多线线程
时间: 2023-10-12 16:09:22 浏览: 34
Python 有多种方式可以实现多线程采集。以下是其中一种基于 `threading` 模块的示例代码:
```python
import threading
import requests
class MyThread(threading.Thread):
def __init__(self, url):
threading.Thread.__init__(self)
self.url = url
def run(self):
response = requests.get(self.url)
print(response.text)
urls = ["https://www.google.com", "https://www.baidu.com", "https://www.yahoo.com"]
threads = []
for url in urls:
t = MyThread(url)
threads.append(t)
t.start()
for t in threads:
t.join()
```
以上代码定义了一个 `MyThread` 类,该类继承自 `threading.Thread` 类。在 `MyThread` 类中,我们重写了 `run()` 方法,用于执行线程任务:请求给定的 URL 并打印响应内容。
然后,我们创建了多个 `MyThread` 实例,每个实例都传入不同的 URL。这些实例被添加到 `threads` 列表中,并逐个调用 `start()` 方法启动线程。
最后,我们使用 `join()` 方法等待所有线程执行完毕。