如何在Google News URL中指定日期范围?urllib爬取结果异常
问题解决:Google News指定日期爬取失效
问题说明
手动将指定日期范围的Google News搜索URL粘贴到Chrome浏览器,能正常获取2018年11月26日至2018年12月26日的可口可乐相关新闻,但使用urllib爬取时,仅返回最新文章。代码片段如下:
from urllib.request import Request, urlopen from urllib.parse import quote from bs4 import BeautifulSoup import requests import ssl ssl._create_default_https_context = ssl._create_unverified_context query = 'coca cola' query_url = quote(query) start_date = datetime.date(2018, 11, 26).strftime('%m/%d/%Y') end_date = datetime.date(2018, 12, 26).strftime('%m/%d/%Y') root = "https://www.google.com/" link = f"https://www.google.com/search?start=0&q={query_url}&tbm=nws&tbs=cdr:1,cd_min:{start_date},cd_max:{end_date},sbd:1&lr=lang_en" def news(link): req = Request(link, headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() with requests.Session() as c: soup = BeautifulSoup(webpage, 'html.parser')
问题原因
- 请求头不完整:仅设置
User-Agent不足以通过Google的反爬验证,Google会识别出非浏览器请求,返回默认的最新结果。 - 模块混用且逻辑冗余:同时使用
urllib和requests,且requests.Session未实际用于请求,只是用来初始化BeautifulSoup,完全没必要。 - 缺少必要模块导入:代码中使用了
datetime.date但未导入datetime模块,会直接引发运行错误。
解决方法
1. 完善请求头,模拟真实浏览器
添加Accept、Accept-Language、Referer等常见浏览器请求头,让请求更接近真实用户行为。
2. 统一使用requests库
requests库在处理会话、请求头和响应时更简洁易用,避免urllib和requests混用的混乱。
3. 修复模块导入问题
补充datetime模块的导入。
修正后的代码
from urllib.parse import quote from bs4 import BeautifulSoup import requests import ssl import datetime # 补充导入datetime模块 ssl._create_default_https_context = ssl._create_unverified_context query = 'coca cola' query_url = quote(query) start_date = datetime.date(2018, 11, 26).strftime('%m/%d/%Y') end_date = datetime.date(2018, 12, 26).strftime('%m/%d/%Y') link = f"https://www.google.com/search?start=0&q={query_url}&tbm=nws&tbs=cdr:1,cd_min:{start_date},cd_max:{end_date},sbd:1&lr=lang_en" def news(link): # 完善请求头,模拟Chrome浏览器 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Referer': 'https://www.google.com/' } # 使用requests发送请求 with requests.Session() as session: response = session.get(link, headers=headers, verify=False) response.raise_for_status() # 检查请求是否成功 soup = BeautifulSoup(response.text, 'html.parser') # 解析新闻标题与链接 for item in soup.select('div.Gx5Zad > div > a'): title = item.h3.text news_link = item['href'] print(f"标题: {title}\n链接: {news_link}\n") # 调用函数 news(link)
额外提示
- 如果仍然出现问题,可以从浏览器开发者工具中复制完整的请求头(包括Cookie)添加到代码中,但Cookie可能会过期,需要定期更新。
- Google的反爬机制会不断更新,若长期爬取建议使用官方提供的API,避免触发反爬限制。
内容的提问来源于stack exchange,提问作者anasta.sita
相关产品推荐
相关产品推荐

