我试图在django中使用python请求库进行谷歌查询,但它无法正常工作

时间:2016-05-04 18:11:12

标签: python django python-requests

我正在使用python请求库从谷歌进行查询。但它不起作用。在我发布之前,我在stackoverflow here上发现了另一篇帖子,但它也没有用。我认为使用谷歌在网址中进行查询的方式已经发生了变化,但我只是这么新,我不知道它是什么。继承我的代码

def index(request):

        url = ('https://www.google.com/webhp?hl=en#hl=en&q=stackoverflow')
        google = requests.get(url)
        bs = BeautifulSoup(google.content)
        d = bs.title.string


        links = []
        for link in bs.findAll('a'):
            links.append((
                link.text,
                link.get('href'),
                # link.get('src')
            )
        )


        # return HttpResponse('<pre>' + r.text + '</pre>')
        context = {

            "links": links,
        }
        return render(request, 'index.html', context)

并在我的模板中

 {% for l in links %}
   {{l}}<br>
 {% endfor %}

这是输出

    ('https://maps.google.com/maps?hl=en&tab=wl',)
    ('https://play.google.com/?hl=en&tab=w8',)
    ('https://www.youtube.com/?hl=en&tab=w1',)
    ('https://news.google.com/nwshp?hl=en&tab=wn',)
    ('https://mail.google.com/mail/?tab=wm',)
    ('https://drive.google.com/?tab=wo',)
    ('https://www.google.com/intl/en/options/',)
    ('http://www.google.com/history/optout?hl=en',)
    ('/preferences?hl=en',)
    ('https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/webhp%3Fhl%3Den',)
    ('/search?site=webhp&ie=UTF-8&q=Jane+Jacobs&oi=ddle&ct=jane-jacobss-100th-birthday-5122456077467648-hp&hl=en&sa=X&ved=0ahUKEwjinsHMgMHMAhVKPz4KHVX_CLsQNggD',)
    ('/advanced_search?hl=en&authuser=0',)
    ('/language_tools?hl=en&authuser=0',)
    ('/intl/en/ads/',)
    ('/services/',)
    ('https://plus.google.com/116899029375914044550',)
    ('/intl/en/about.html',)
    ('/intl/en/policies/privacy/',)
    ('/intl/en/policies/terms/',)

这似乎是谷歌主页,但它与我查询的内容不符。我应该得到一个与stackoverflow有关的文章列表。我怎样才能解决这个问题?为了清楚起见,我想通过查询我的选择查询谷歌并抓取链接并将其显示在我的模板上

1 个答案:

答案 0 :(得分:0)

1)您是否查看了您试图抓取的页面来源?我没有看到生成的HTML中的链接 2)您可能必须使用Selenium或类似的东西。首先,您没有定义用户代理。谷歌设计了它的页面以阻止这些努力