Python爬虫脚本:从文章列表中提取图片数据
以下是一个使用Python爬虫脚本来爬取文章列表中的图片数据的示例:\n\npython\nimport requests\nfrom bs4 import BeautifulSoup\n\n# 创建一个会话\nsession = requests.Session()\n\n# 设置请求头\nheaders = {'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'}\n\n# 获取文章列表页面的HTML内容\nresponse = session.get('https://example.com/article-list', headers=headers)\nhtml_content = response.content\n\n# 使用BeautifulSoup解析HTML内容\nsoup = BeautifulSoup(html_content, 'html.parser')\n\n# 查找所有的文章链接\narticle_urls = soup.find_all('a', target='_blank', href=lambda href: href and 'www.hellorf.com/image/show/' in href)\n\n# 遍历每个文章链接\nfor article_url in article_urls:\n # 获取图片页面的HTML内容\n response = session.get(article_url['href'], headers=headers)\n html_content = response.content\n\n # 使用BeautifulSoup解析HTML内容\n soup = BeautifulSoup(html_content, 'html.parser')\n\n # 查找图片标签\n image_tags = soup.find_all('img')\n\n # 遍历每个图片标签\n for image_tag in image_tags:\n # 获取图片链接并保存图片\n image_url = image_tag['src']\n response = session.get(image_url, headers=headers)\n\n # 根据需要保存图片的路径和文件名\n file_path = '/path/to/save/images/'\n file_name = 'image{}.jpg'.format(len(os.listdir(file_path)))\n\n with open(file_path + file_name, 'wb') as f:\n f.write(response.content)\n print('图片已保存:', file_name)\n\n\n请注意,这只是一个示例脚本,你需要根据实际情况进行修改和调整。
原文地址: https://www.cveoy.top/t/topic/pOp5 著作权归作者所有。请勿转载和采集!