写一串python爬网页图片的代码
时间: 2023-04-08 19:02:37 浏览: 54
以下是一段简单的 Python 代码,用于爬取网页上的图片:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for img in soup.find_all('img'):
img_url = img.get('src')
img_response = requests.get(img_url)
with open(img_url.split('/')[-1], 'wb') as f:
f.write(img_response.content)
```
这段代码使用 requests 库获取网页内容,使用 BeautifulSoup 库解析 HTML,然后遍历所有的 img 标签,获取图片的 URL,再使用 requests 库下载图片并保存到本地。
相关问题
写一段python爬虫代码爬取网页图片
以下是一个简单的Python爬虫代码,可以爬取指定网页的图片并将其保存到本地:
```python
import requests
from bs4 import BeautifulSoup
import os
url = 'https://example.com' # 指定要爬取的网页
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
# 查找所有图片标签
img_tags = soup.find_all('img')
# 遍历所有图片标签,下载图片并保存到本地
for img_tag in img_tags:
img_url = img_tag.get('src')
img_name = img_url.split('/')[-1] # 图片名称为url中最后一个斜杠后的字符串
img_path = os.path.join('./images', img_name) # 保存到当前目录下的images文件夹中
img_res = requests.get(img_url)
with open(img_path, 'wb') as f:
f.write(img_res.content)
print(f'Saved {img_name} successfully.')
```
请注意,此代码仅供参考,实际使用时需要根据具体情况进行修改和优化。同时,爬取网页内容可能涉及法律风险,请谨慎使用。
python爬虫网页数据抓取
Python爬虫是一种用于自动化采集网络上的数据的技术,可以获取网页内容、图片、视频、音频等数据。在实际的爬虫应用中,为了避免被网站识别为爬虫,我们可以使用Request来伪装请求头。
以下是一个简单的Python爬虫网页数据抓取的示例:
```python
import urllib.request
# 设置请求头
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'
}
# 发起请求
url = 'https://www.example.com' # 替换为你要抓取的网页地址
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
# 读取响应内容
data = response.read()
# 打印网页内容
print(data.decode('utf-8'))
```
这段代码中,我们首先设置了请求头,其中User-Agent字段用于伪装浏览器的请求头。然后,我们使用urllib.request.Request()函数创建一个请求对象,并传入URL和请求头。接下来,使用urllib.request.urlopen()函数发起请求,并将响应保存在response变量中。最后,我们使用response.read()方法读取响应内容,并使用decode()方法将其转换为字符串格式。最终,我们打印出网页内容。