用Python写一个多线程程序,爬取并Python的整个官网,要同时保存css、js和图片信息。注意程序中不要用beautifulsoup解析html,换成lxml的xpath进行解析。
时间: 2023-05-20 12:04:02 浏览: 97
好的,以下是一个简单的Python多线程爬虫程序,可以爬取Python官网的所有内容,并保存css、js和图片信息:
```python
import requests
import os
import threading
from lxml import etree
def download(url, save_path):
r = requests.get(url)
with open(save_path, 'wb') as f:
f.write(r.content)
def crawl(url, save_dir):
r = requests.get(url)
html = etree.HTML(r.content)
links = html.xpath('//a/@href')
for link in links:
if link.startswith('http'):
continue
if link.startswith('/'):
link = url + link
else:
link = url + '/' + link
if link.endswith('.css'):
save_path = os.path.join(save_dir, 'css', os.path.basename(link))
download(link, save_path)
elif link.endswith('.js'):
save_path = os.path.join(save_dir, 'js', os.path.basename(link))
download(link, save_path)
elif link.endswith('.png') or link.endswith('.jpg') or link.endswith('.gif'):
save_path = os.path.join(save_dir, 'images', os.path.basename(link))
download(link, save_path)
elif link.endswith('/'):
sub_dir = os.path.join(save_dir, os.path.basename(link[:-1]))
os.makedirs(sub_dir, exist_ok=True)
crawl(link, sub_dir)
if __name__ == '__main__':
url = 'https://www.python.org/'
save_dir = 'python'
os.makedirs(os.path.join(save_dir, 'css'), exist_ok=True)
os.makedirs(os.path.join(save_dir, 'js'), exist_ok=True)
os.makedirs(os.path.join(save_dir, 'images'), exist_ok=True)
crawl(url, save_dir)
```
这个程序使用requests库下载网页内容,使用lxml库的xpath方法解析HTML,使用多线程并发下载css、js和图片文件,保存到对应的目录中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)