如何使用Python爬取Google News文章图片并在Django模板中展示?
问题解决方案
核心错误原因
- 未携带请求头触发谷歌反爬机制:直接调用
requests.get()时默认的请求头会被谷歌识别为爬虫,返回的页面结构和正常浏览器访问结果完全不同。你代码中用到的qV9w7d类是前端JS动态渲染后才生成的,静态请求返回的HTML里不存在该类,所以查询结果为空。 - 元素定位逻辑错误:你当前代码检索的是类为
qV9w7d的div容器,没有进一步提取容器下的img标签,自然拿不到预期的img元素数据。
修改后的代码示例
from django.shortcuts import render import requests from bs4 import BeautifulSoup def index(request): URL = 'https://www.google.com/search?q=beyond+meat&rlz=1C1CHBF_enUS898US898&sxsrf=ALeKk00IH9jp1Kz5-LSyi7FUB4rd6--_hw:1624935518812&source=lnms&tbm=nws&sa=X&ved=2ahUKEwicqIbD7LvxAhVWo54KHXgRA9oQ_AUoAXoECAEQAw&biw=1536&bih=754' # 新增请求头模拟浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } page = requests.get(URL, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') headers = soup.find_all('div', class_='BNeawe vvjwJb AP7Wnd') header_dict = [h.text for h in headers] # 调整定位逻辑,直接检索新闻条目下的img标签 images = [] news_items = soup.find_all('div', role='article') for item in news_items: img = item.find('img') if img: images.append(str(img)) # 转换为字符串就是你需要的img标签HTML格式 context= { "header_dict": header_dict, "example": images, } return render(request, 'index.html', context)
注意事项
谷歌新闻的类名会不定期更新,如果修改后还是拿不到数据,可以先打印
soup.prettify()查看返回的实际页面结构,找到img标签对应的正确属性再调整定位规则。
拿到img的src属性后要注意,谷歌返回的部分图片是相对路径,需要拼接https://www.google.com域名前缀才能正常在Django模板中展示。
内容的提问来源于stack exchange,提问作者melandalin
相关产品推荐
相关产品推荐

