写一段python爬取网页图片的代码
时间: 2023-04-10 21:05:07 浏览: 74
以下是一段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)
```
这段代码可以爬取网页中所有的图片,并将其保存到本地。
相关问题
写一段python爬取网页的代码
好的,以下是一个简单的Python爬取网页的代码示例,使用了requests和BeautifulSoup库:
```python
import requests
from bs4 import BeautifulSoup
# 发送HTTP请求并获取响应内容
response = requests.get('https://www.example.com')
# 解析HTML内容
soup = BeautifulSoup(response.content, 'html.parser')
# 获取网页标题
title = soup.title.text
# 输出网页标题
print(title)
```
这段代码会发送一个HTTP GET请求到指定的URL,并从响应中获取HTML内容。然后使用BeautifulSoup库解析HTML内容,并提取出网页标题。最后输出网页标题。当然,这只是一个简单的示例,实际的爬虫可能需要更多的代码来处理不同的情况。
写一段Python爬取数据的代码
当然,我很乐意帮你写一段Python爬取数据的代码。以下是一个简单的示例,使用 Python 的 requests 和 BeautifulSoup 库来获取并解析网页内容:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
# 输出网页标题
print(soup.title.string)
# 输出所有链接
for link in soup.find_all('a'):
print(link.get('href'))
```
这段代码会向 https://www.example.com 发送一个 GET 请求,并用 BeautifulSoup 解析 HTML 内容。然后,它会输出网页标题和所有链接。当然,你可以根据自己的需求修改这个代码,来爬取你需要的数据。