import requests from bs4 import BeautifulSoup # 发起网络请求,获取 HTML 页面 response = requests.get('http://example.com/images') # 使用 BeautifulSoup 解析 HTML 页面 soup = BeautifulSoup(response.text, 'html.parser') # 找到所有图片链接 image_tags = soup.find_all('img') # 遍历图片链接,下载图片 for image_tag in image_tags: image_url = image_tag['src'] response = requests.get(image_url) with open('image.jpg', 'wb') as f: f.write(response.content)
时间: 2023-02-06 20:50:50 浏览: 157
import requests
from bs4 import BeautifulSoup
这些语句用于导入 Python 中的两个模块:
- requests 模块是用于发送 HTTP 请求的模块。通过使用 requests 模块,你可以发送 GET 请求、POST 请求、PUT 请求、DELETE 请求等等。
- BeautifulSoup 是用于解析 HTML 和 XML 文档的库。通过使用 BeautifulSoup,你可以方便地解析文档,提取出你需要的信息。
通常,你需要先通过 requests 模块发送 HTTP 请求,然后使用 BeautifulSoup 解析响应内容。例如,你可以这样做:
```
import requests
from bs4 import BeautifulSoup
response = requests.get('http://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
```
上面的代码发送了一个 GET 请求到 http://example.com,然后使用 BeautifulSoup 解析了响应的 HTML 内容。
相关问题
给出解析<a href="/v3/download/excel?filecode=N2021050062000004" download> <img src="/v3/resources/design/images/nS_down2.png"> </a>链接的代码
好的,以下是一个 Python 代码段,可以解析给定 HTML 页面中的下载链接,并将其保存到本地:
```python
import requests
from bs4 import BeautifulSoup
# 要解析的页面 URL
url = 'https://example.com/page.html'
# 发送 HTTP GET 请求,获取页面内容
response = requests.get(url)
html = response.text
# 使用 BeautifulSoup 解析页面 HTML
soup = BeautifulSoup(html, 'html.parser')
# 查找所有的下载链接
download_links = soup.find_all('a', {'download': True})
# 下载每个链接中的文件
for link in download_links:
# 获取文件名和下载链接
file_name = link['href'].split('/')[-1]
download_url = urljoin(url, link['href'])
# 发送 HTTP GET 请求,下载文件
response = requests.get(download_url)
# 保存文件
with open(file_name, 'wb') as f:
f.write(response.content)
print(f'{file_name} 下载完成')
```
在上面的代码中,我们首先使用 requests 库发送 HTTP GET 请求,获取指定页面的 HTML 内容。然后,使用 BeautifulSoup 库解析页面 HTML,并查找所有带有 `download` 属性的链接。最后,我们使用 requests 库下载每个链接中的文件,并将其保存到本地。
python requests bs4爬取网络图片
使用 Python 中的 requests 和 Beautiful Soup 库可以轻松地爬取网络图片。以下是一个简单的示例,可以爬取指定网页中所有的图片,并将其保存到本地文件夹中:
```
import os
import requests
from bs4 import BeautifulSoup
# 网页 URL
url = "https://www.example.com"
# 请求头部信息,模拟浏览器请求
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
# 发送 GET 请求
response = requests.get(url, headers=headers)
# 解析 HTML 页面
soup = BeautifulSoup(response.content, 'html.parser')
# 找到所有的图片标签
img_tags = soup.find_all('img')
# 遍历所有的图片标签,依次下载图片
for img_tag in img_tags:
# 获取图片链接
img_url = img_tag.get('src')
# 发送 GET 请求,获取图片数据
img_response = requests.get(img_url)
# 获取图片名称
img_name = os.path.basename(img_url)
# 保存图片到本地文件夹
with open(f"images/{img_name}", "wb") as f:
f.write(img_response.content)
print(f"Saved {img_name} successfully!")
```
需要注意的是,这段代码中的网页 URL 和请求头部信息需要根据实际情况进行修改。另外,需要确保本地文件夹 images 存在并且有写权限,否则保存图片会失败。