python爬虫小程序
时间: 2023-09-22 18:06:00 浏览: 56
以下是一个简单的Python爬虫小程序,用于爬取网页上的图片:
```python
import requests
import os
from urllib.parse import urlparse
def download_images(url):
response = requests.get(url)
html = response.text
urls = re.findall(r'(http[s]?://\S+jpg|png)', html)
for i in range(len(urls)):
url = urls[i]
parse_result = urlparse(url)
filename = os.path.basename(parse_result.path)
try:
image_data = requests.get(url).content
with open(filename, 'wb') as handler:
handler.write(image_data)
except:
pass
if __name__ == '__main__':
url = input('请输入要爬取的网址:')
download_images(url)
```
该程序通过requests库获取网页的html代码,并使用正则表达式解析出其中的图片链接。然后通过urllib库中的urlparse函数将图片链接解析为文件名,再通过requests库下载图片并保存到本地。最后,用户输入要爬取的网址即可启动程序。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)