网页抓取Google - 获得不同的结果

时间:2016-05-13 17:28:08

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

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

E.g。该脚本不是显示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)

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

我做了一些测试,似乎问题来自用户代理,这个问题不够详细。 尝试替换此行:

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"),

它对我有用。 当然,这个用户代理只是一个例子。

相关问题