【问题标题】:Google news crawler to return results with url,title and briefing谷歌新闻爬虫返回带有网址、标题和简报的结果
【发布时间】:2017-09-30 16:40:32
【问题描述】:

我是爬虫新手,我正在使用 Python 3.X。目前我正在练习抓取谷歌新闻以重新开始,但我的代码遇到了一些问题(代码运行但没有返回任何内容)。我希望代码抓取谷歌新闻进行查询并返回结果中出现的 url、标题和简报。

非常感谢您的宝贵时间。我的代码如下:

import sys
import urllib
import requests
from bs4 import BeautifulSoup
import time

s = "Stack Overflow"
url = "http://www.google.com.sg/search?q="+s+"&tbm=nws&tbs=qdr:y"
#htmlpage = urllib2.urlopen(url).read()
time.sleep(randint(0, 2))
htmlpage = requests.get(url)
soup = BeautifulSoup(htmlpage.text,'lxml')
#print (len(soup.findAll("table", {"class": "result"})))
for result_table in soup.findAll("table", {"class": "result"}):
    a_click = result_table.find("a")
    print ("-----Title----\n" + a_click.renderContents())#Title
    print ("----URL----\n" + str(a_click.get("href")))#URL
    print ("----Brief----\n" + result_table.find("div", {"class": "c-abstract"}).renderContents())#Brief
    print ("Done")

【问题讨论】:

  • 不是指向您的代码的链接,您可以编辑它并直接将其粘贴到问题中吗?然后告诉我们您认为可能出错的地方以及您遇到的问题,然后根据您的帖子标题提出一个问题..
  • 谢谢提醒,我已经提供了代码。我被我的代码卡住了,根本没有打印结果的 url、标题和简报。

标签: python python-3.x web-crawler google-crawlers google-news


【解决方案1】:

这就是我得到结果的方式,希望对您有所帮助:

>>> for result_table in soup.findAll("div", {"class": "g"}):
...     a_click = result_table.find("a")
...     print ("-----Title----\n" + str(a_click.renderContents()))#Title
...     print ("----URL----\n" + str(a_click.get("href")))#URL
...     print ("----Brief----\n" + str(result_table.find("div", {"class": "st"}).renderContents()))#Brief
...     print ("Done")
... 
-----Title----
b"<b>Stack Overflow</b>: Like sleep? Don't code in C"
----URL----
/url?q=http://www.infoworld.com/article/3190701/application-development/stack-overflow-like-sleep-dont-code-in-c.html&sa=U&ved=0ahUKEwjc34W_3NLTAhVIMY8KHVu_BoUQqQIIFigAMAA&usg=AFQjCNE7xDqkg-kyFR65krfMIJqIchHFwg
----Brief----
b'In analysis of programming traffic on the <b>Stack Overflow</b> online community over for four weeks last August, <b>Stack Overflow</b> Insights data scientist David Robinson,\xc2\xa0...'
Done

【讨论】:

  • 谢谢你!现在假设我想要“Stack+Overflow”的确切结果,我应该如何更改代码? make s="Stack+Overflow" 似乎不起作用
  • 解决了,把s="Stack+Overflow"改成s='"Stack+Overflow"'就可以了!
  • 优秀的文章。我知道这是真的。 Arduino 编程成为您不想中断的工作流程。对于桌面机器上的真正 C++ 程序,有很多东西要记住,比如指针和变量名,而不是让任性的花括号和缩进变得清晰,以及你记住的类,你必须去复习它们以记住所有方法是的,入睡意味着在醒来时必须重新学习自己的代码(以及您可能借用的所有库),从而浪费宝贵的编程时间。 ;-)
  • 这是我在 CS 学校时的一次爆炸。真正的程序员使用 Fortran。修改是因为他们让我们使用 Pascal:web.mit.edu/humor/Computers/real.programmers
  • 嗨,JkShaw,很抱歉再次打扰您,我意识到代码只能抓取结果的第 1 页,而不是所有结果。爬取页面中的所有结果是否需要添加任何内容?
猜你喜欢
  • 1970-01-01
  • 2013-10-15
  • 1970-01-01
  • 2022-01-06
  • 2013-06-22
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多