在Python中读取图片链接通常涉及以下步骤:
1. 使用`requests`库获取网页源代码。
2. 使用`BeautifulSoup`解析HTML内容。
3. 查找所有`img`标签并提取`src`属性,即图片链接。
4. (可选)过滤链接,只保留特定格式的图片(如.jpg、.png)。
5. (可选)为没有`http:`前缀的链接添加协议头。
6. (可选)下载图片到本地。
import requestsfrom bs4 import BeautifulSoupdef get_image_urls(url):response = requests.get(url)html_doc = response.content.decode()soup = BeautifulSoup(html_doc, 'html.parser')img_tags = soup.find_all('img')image_urls = [img.get('src') for img in img_tags]return image_urls示例使用image_urls = get_image_urls('http://example.com')print('Image URLs:', image_urls)
如果你需要下载这些图片,可以继续使用`requests`库:
import osdef download_image(url, save_path):response = requests.get(url)if response.status_code == 200:with open(save_path, 'wb') as f:f.write(response.content)示例使用download_image(image_urls, 'example_image.jpg')
请注意,在处理网页时,可能需要模拟浏览器的行为,比如设置`User-Agent`头,以避免被网站识别为爬虫并拒绝服务。

