生成一个自动爬取某个网站所有图片的爬虫
时间: 2023-02-28 08:56:58 浏览: 90
编写一个爬虫来自动爬取某个网站的图片需要使用编程语言和爬虫框架。下面是用 Python 编写的示例代码,使用了 BeautifulSoup 库和 Requests 库。
```
import requests
from bs4 import BeautifulSoup
def get_images(url):
# 发送 GET 请求,获取网页源代码
resp = requests.get(url)
html = resp.text
soup = BeautifulSoup(html, 'html.parser')
# 找到所有图片的 <img> 标签
imgs = soup.find_all('img')
# 遍历每个 <img> 标签,提取图片的 URL 并下载图片
for img in imgs:
img_url = img['src']
img_resp = requests.get(img_url)
with open(f'{img_url.split("/")[-1]}', 'wb') as f:
f.write(img_resp.content)
# 调用 get_images() 函数,爬取网页上的图片
get_images('https://www.example.com')
```
这段代码可以爬取某个网站的图片,并将图片保存到当前目录下。你可以修改这段代码以适应你的需求。
相关问题
用Python写一个爬取pixiv网站图片的爬虫
好的,以下是一个简单的爬取pixiv网站图片的Python爬虫:
```python
import requests
from bs4 import BeautifulSoup
import os
# 图片保存路径
save_path = "./pixiv_images"
# 爬取页面的URL
url = "https://www.pixiv.net/ranking.php"
# 请求头信息
headers = {
"Referer": "https://www.pixiv.net/",
"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"}
# 发送请求,获取页面内容
response = requests.get(url, headers=headers)
# 解析HTML
soup = BeautifulSoup(response.text, "html.parser")
# 获取图片链接
img_tags = soup.select("img[src^='https://i.pximg.net']")
# 创建文件夹
if not os.path.exists(save_path):
os.makedirs(save_path)
# 下载图片
for i, img_tag in enumerate(img_tags):
img_url = img_tag["src"]
response = requests.get(img_url, headers=headers)
with open(os.path.join(save_path, f"pixiv_{i}.jpg"), "wb") as f:
f.write(response.content)
print("图片下载完成!")
```
该爬虫使用requests库发送HTTP请求,使用BeautifulSoup库解析HTML,使用os库创建文件夹,遍历图片链接并下载图片。请注意,该爬虫只是一个简单的示例,并不一定能够爬取所有的pixiv图片。
帮我写一个爬取百度图片的python爬虫
以下是一个基本的爬取百度图片的Python爬虫:
```python
import requests
import os
def download_pic(pic_url, save_path):
response = requests.get(pic_url)
with open(save_path, 'wb') as f:
f.write(response.content)
def search_and_download(keyword, download_path):
url = 'https://image.baidu.com/search/index?tn=baiduimage&word={}'.format(keyword)
response = requests.get(url)
pic_urls = response.json()['data']
for i, pic_info in enumerate(pic_urls):
pic_url = pic_info['large_image_url']
save_path = os.path.join(download_path, '{}.jpg'.format(i))
download_pic(pic_url, save_path)
if __name__ == '__main__':
keyword = '猫'
download_path = './download'
if not os.path.exists(download_path):
os.mkdir(download_path)
search_and_download(keyword, download_path)
```
该爬虫首先构造了一个百度图片搜索的URL,然后发送请求获取搜索结果,解析出每张图片的URL,并下载保存到本地。需要注意的是,由于百度图片的URL可能会变化,因此该爬虫并不一定能够一直正常工作。