使用python3 格式为def 编写按行读取url.txt为host变量 dir.txt为拼接组合 多线程访问 如果响应码为200 自动下载保存命名为host变量名.txt
时间: 2023-06-15 07:03:58 浏览: 89
以下是可能的代码实现:
```python
import requests
import threading
def download_url(url):
response = requests.get(url)
if response.status_code == 200:
host = url.split('//')[-1].split('/')[0]
file_name = f'{host}.txt'
with open(file_name, 'w', encoding='utf-8') as f:
f.write(response.text)
def read_urls():
with open('url.txt', 'r') as f:
urls = f.readlines()
urls = [url.strip() for url in urls]
return urls
def read_dirs():
with open('dir.txt', 'r') as f:
dirs = f.readlines()
dirs = [dir.strip() for dir in dirs]
return dirs
if __name__ == '__main__':
urls = read_urls()
dirs = read_dirs()
threads = []
for url in urls:
for dir in dirs:
full_url = f'{url}/{dir}'
thread = threading.Thread(target=download_url, args=(full_url,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
```
该代码通过 `read_urls` 和 `read_dirs` 函数分别读取 `url.txt` 和 `dir.txt` 文件中的内容,并将其存储在 `urls` 和 `dirs` 变量中。然后它通过循环遍历每个 `url` 和 `dir` 的组合,并将其传递给 `download_url` 函数进行下载。如果响应状态码为200,则该代码会将响应文本保存到名为 `host.txt` 的文件中,其中 `host` 是从 `url` 中提取的主机名。
该代码使用多线程来加速下载过程。每个下载任务都在一个单独的线程中执行,这样可以同时执行多个下载任务。在所有线程完成之后,该代码将退出。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)