python批量下载狗狗图片
时间: 2024-01-24 15:16:02 浏览: 89
使用python批量下载图片
以下是使用Python批量下载狗狗图片的示例代码:
```python
import requests
from lxml import etree
# 获取网页源码
def get_html(url):
response = requests.get(url)
html = response.text
return html
# 解析网页源码,获取图片链接
def get_image_urls(html):
tree = etree.HTML(html)
image_urls = tree.xpath('//*[@id="container"]/div/div/a/img/@src2')
return image_urls
# 下载图片
def download_images(image_urls):
for i, url in enumerate(image_urls):
response = requests.get(url)
with open(f'dog_image_{i+1}.jpg', 'wb') as f:
f.write(response.content)
# 主函数
def main():
url = 'https://www.example.com' # 替换为实际的网页链接
html = get_html(url)
image_urls = get_image_urls(html)
download_images(image_urls)
if __name__ == '__main__':
main()
```
请注意,上述代码中的`url`需要替换为实际的网页链接,以确保能够正确获取到狗狗图片的链接。另外,代码中使用了第三方库`requests`和`lxml`,请确保已经安装了这两个库。
阅读全文