python - 网页抓取谷歌 - 得到不同的结果

标签 python web-scraping beautifulsoup web-crawler python-requests

我编写了以下 Python 脚本,用于在特定日期范围内抓取和抓取 Google 新闻搜索结果的标题。虽然脚本可以正常工作,但它显示的是最新的搜索结果,而不是列表中提到的结果。

例如该脚本显示的不是 2015 年 7 月 1 日至 2015 年 7 月 7 日的结果,而是 2016 年 5 月(当月)的结果

import urllib.request 
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

#get and read the URL
url = ("https://www.google.co.in/search?q=banking&num=100&safe=off&espv=2&biw=1920&bih=921&source=lnt&tbs=cdr%3A1%2Ccd_min%3A01%2F07%2F2015%2Ccd_max%3A07%2F07%2F2015&tbm=nws")
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
html = opener.open(url)
bsObj = BeautifulSoup(html.read(), "html5lib")


#extracts all the links from the given page 
itmes  = bsObj.findAll("h3")
for item in itmes:
    itemA = item.a
    theHeading = itemA.text
    print(theHeading)

有人可以指导我获得按日期排序的所需结果的正确方法吗?

提前致谢。

最佳答案

我做了一些测试,似乎问题出在 User-Agent 上,它不够详细。 尝试替换这一行:

opener.addheaders = [('User-agent', 'Mozilla/5.0')]

与:

opener.addheaders = [('User-agent', "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0"),

它对我有用。 当然这个User-Agent只是一个例子。

关于python - 网页抓取谷歌 - 得到不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37215999/

相关文章:

python - 如何使用 beautifulsoup 提取 onClick url

Python 在遍历列表后删除列表中的一半元素

python - 如何使用子进程和 preexec_fn 处理子 SIGFPE/SIGILL 信号?

python - 无法抓取

python - 无法通过 BeautifulSoup 使用 $0 从 DOM 元素中提取内容

python - 我的正则表达式 "appears"在测试器中工作,但在我的实际代码中不起作用

Python-Selenium : Not able to scrape image from html/javascript string

python - 在 Flask 中使用 joblib 进行并行计算

python - 用python更改MAC地址

python - 解析链接时脚本给出重复结果