python获取图片src
时间: 2023-10-28 08:48:44 浏览: 55
获取网页中图片的src可以使用Python的BeautifulSoup库,具体步骤如下:
1. 导入BeautifulSoup库:`from bs4 import BeautifulSoup`
2. 使用requests库获取网页源码:`response = requests.get(url)`
3. 使用BeautifulSoup解析网页源码:`soup = BeautifulSoup(response.text, 'html.parser')`
4. 使用find_all方法查找所有图片标签:`img_tags = soup.find_all('img')`
5. 遍历图片标签,获取src属性:`for img in img_tags:
print(img['src'])`
注意:在使用该方法时,需要先判断img标签是否存在src属性,否则会出现KeyError异常。
相关问题
python爬虫获取src
回答: 要获取src属性,你可以使用Python爬虫来实现。根据你提供的代码,可以看到你使用了requests库和lxml库来发送HTTP请求和解析HTML。如果你想获取图片的src属性,你可以使用xpath来定位img标签,并使用get方法获取src属性的值。以下是一个示例代码:
```python
import requests
from lxml import etree
# 发送HTTP请求并获取网页源码
response = requests.get('http://xxxxxx.com/xxx?xxx', headers=headers)
html = etree.HTML(response.content.decode())
# 使用xpath获取图片的src属性
img_src = html.xpath("//img/@src")
# 打印获取到的src属性值
for src in img_src:
print(src)
```
如果你想获取其他类型的src属性,可以根据具体的HTML结构和标签来修改xpath表达式。希望这个示例能帮到你。
#### 引用[.reference_title]
- *1* [Python爬虫爬取src图片](https://blog.csdn.net/weixin_54250368/article/details/122192440)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v4^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [python 爬虫如何获取js里面的内容](https://blog.csdn.net/hanchaobiao/article/details/73150405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v4^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
Python爬虫获取图片
Python爬虫获取图片的基本步骤如下:
1. 导入requests、os、re等模块
2. 使用requests库发送请求获取网页源码
3. 使用re模块或BeautifulSoup库解析网页源码,找到图片链接
4. 使用requests库发送请求获取图片二进制数据
5. 将图片保存到本地文件夹中
以下是一个简单的Python爬虫获取图片的示例代码:
```
import requests
import os
import re
url = 'http://www.example.com' # 网站地址
path = './images' # 图片保存路径
if not os.path.exists(path):
os.makedirs(path)
# 发送请求获取网页源码
response = requests.get(url)
html = response.text
# 使用正则表达式或BeautifulSoup库解析网页源码,找到图片链接
img_urls = re.findall(r'src="(.*?\.(jpg|png))"', html)
# 发送请求获取图片二进制数据,并保存到本地文件夹中
for img_url in img_urls:
img_name = img_url.split('/')[-1]
img_path = os.path.join(path, img_name)
img_response = requests.get(img_url)
with open(img_path, 'wb') as f:
f.write(img_response.content)
print('成功下载图片:', img_name)
```