黑马程序员 多线程爬虫基本实例
时间: 2023-07-26 19:17:16 浏览: 73
好的,这里是一个基本的多线程爬虫实例:
```python
import requests
from threading import Thread
class Spider(Thread):
def __init__(self, url):
Thread.__init__(self)
self.url = url
def run(self):
response = requests.get(self.url)
print(response.content)
if __name__ == '__main__':
urls = ['https://www.baidu.com', 'https://www.google.com', 'https://www.github.com']
threads = []
for url in urls:
spider = Spider(url)
threads.append(spider)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
```
这个实例中,我们先定义了一个 `Spider` 类继承自 `Thread`,并重写了 `Thread` 的 `run` 方法。在 `run` 方法中,我们使用 `requests` 库发送了一个 HTTP 请求,并打印了请求返回的内容。
在 `main` 函数中,我们定义了一个包含三个 URL 的列表 `urls`,然后创建了三个 `Spider` 的线程分别去请求这三个 URL,并将这些线程加入到一个列表 `threads` 中。接着我们启动这些线程,并等待它们全部执行完毕后再退出程序。
通过这个例子,我们可以看到如何使用多线程来提高爬取数据的效率。