使用python爬取网站上的图片
时间: 2024-06-10 14:04:41 浏览: 21
好的,可以使用Python中的Requests和BeautifulSoup库来实现网站图片的爬取。
首先,需要用Requests库发送HTTP请求,获取网页的HTML源码。然后,用BeautifulSoup库解析HTML源码,找到图片的链接。最后,用Requests库下载图片并保存到本地即可。
以下是一个简单的爬取网站图片的Python代码示例:
```
import requests
from bs4 import BeautifulSoup
url = 'https://example.com' # 替换为你需要爬取的网站链接
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
for img in img_tags:
img_url = img['src']
if img_url.startswith('http'):
img_response = requests.get(img_url)
img_data = img_response.content
with open('image.jpg', 'wb') as f:
f.write(img_data)
```
这段代码将会爬取指定网站中的所有图片,并保存在当前目录下的`image.jpg`文件中。
相关问题
python爬取网站图片
要爬取网站的图片,可以使用 Python 的 requests 和 BeautifulSoup 库来实现。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import os
# 目标网站的 URL
url = "https://www.example.com"
# 发送 GET 请求
response = requests.get(url)
# 解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 创建保存图片的目录
if not os.path.exists('images'):
os.makedirs('images')
# 遍历所有的图片标签
for img in soup.find_all('img'):
# 获取图片的 URL
img_url = img.get('src')
if not img_url:
continue
# 发送 GET 请求
img_response = requests.get(img_url)
# 保存图片
with open('images/' + os.path.basename(img_url), 'wb') as f:
f.write(img_response.content)
```
上述代码中,我们首先发送 GET 请求获取网站的 HTML 内容,然后使用 BeautifulSoup 解析 HTML,找到所有的图片标签,获取图片的 URL,并发送 GET 请求获取图片内容,最后将图片保存到本地目录中。注意要判断图片是否存在 URL,以及创建保存图片的目录。
如何使用Python爬取图片?
以下是使用Python爬取图片的两种方法:
1. 使用urllib库和正则表达式爬取图片[^1]:
```python
import urllib.request
import re
def download_image(url, save_path):
response = urllib.request.urlopen(url)
image_data = response.read()
with open(save_path, 'wb') as f:
f.write(image_data)
def crawl_images(url):
html = urllib.request.urlopen(url).read().decode('utf-8')
img_urls = re.findall(r'<img.*?src="(.*?)".*?>', html)
for img_url in img_urls:
if img_url.startswith('http'):
download_image(img_url, img_url.split('/')[-1])
# 调用函数进行爬取
crawl_images('http://example.com')
```
2. 使用requests库和json解析爬取图片[^2]:
```python
import requests
import json
class BaiduSpider:
def __init__(self):
self.url = 'http://example.com?page={}&number={}'
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
def parse_html(self, url):
img_html = requests.get(url=url, headers=self.headers).text
img_json = json.loads(img_html)
print(img_json)
def crawl(self):
page = 185 // 30 if 185 % 30 == 0 else 185 // 30 + 1
for number in range(page):
pn = number * 30
self.parse_html(self.url.format(pn, number))
# 调用函数进行爬取
baidu = BaiduSpider()
baidu.crawl()
```