我编写了以下 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/