这可能看起来像是与从news.google.com抓取内容有关的其他问题的重复,但这并不是因为它们只请求整个html代码,而不是文章的url链接。
我正在尝试创建两个函数,它们可以从news.google.com中删除新闻,或者根据用户输入的内容获取新闻,即:
>>> news top
> <5 url of top stories in news.google.com>或
>>> news london
> <5 london related news url from news.google.com>下面是我正在进行的代码工作(因为我对抓取/请求不是很熟悉,所以我不知道如何进行):
def get_news(user_define_input):
try:
response = requests.get("https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q=test&oq="+format(user_define_input[1]))
except:
print ("Error while retrieving data!")
return
tree = html.fromstring(response.text)
news = tree.xpath("//div[@class='l _HId']/text()")
print (news)我确实意识到/text()没有得到url,但我不知道是怎么回事,因此出现了这个问题。
如果需要,您可以添加此代码以使其看起来更好:
news = "<anything>".join(news)为了把事情弄清楚,user_define_input[0]应该是用户输入的“新闻”。而伦敦将是搜索结果,即:“user_define_input[1]”。因此,所有结果都应该与伦敦相关。如果你愿意花时间让我的其他函数从news.google.com获取所有的头条新闻,非常感谢!:) (它应该是类似的代码,所以我不会在这里发布任何相关的东西)
帮助后的代码(仍然不起作用):
def get_news(user_define_input):
try:
response = requests.get("https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q=test&oq="+format(user_define_input[1]))
except:
print ("Error while retrieving data!")
return
tree = html.fromstring(response.text)
url_to_news = tree.xpath(".//div[@class='esc-lead-article-title-wrapper']/h2[@class='esc-lead-article-title']/a/@href")
for url in url_to_news:
print(url)
summary_of_the_new = tree.xpath(".//div[@class='esc-lead-snippet-wrapper']/text()")
title_of_the_new = tree.xpath(".//span[@class='titletext']/text()")
print (summary_of_the_new)
print (title_of_the_new)发布于 2015-08-03 12:30:05
我知道你想要的是获取当用户输入query时出现的所有新闻的url,对吗?
要实现这一点,您需要以下xpath表达式:
url_to_news = tree.xpath(".//div[@class='esc-lead-article-title-wrapper']/h2[@class='esc-lead-article-title']/a/@href")它将返回一个带有新闻url的列表。
因为它是一个列表,所以要遍历urls,您只需要一个for循环:
for url in url_to_news:
print(url)附加组件:
要获取新闻摘要,您需要执行以下操作:
summary_of_the_new = tree.xpath(".//div[@class='esc-lead-snippet-wrapper']/text()")最后,新闻的标题是:
title_of_the_new = tree.xpath(".//span[@class='titletext']/text()")之后,您可以将所有这些信息映射到一起。如果您需要进一步的帮助,请评论此答案。我根据我的理解回答了这个问题。
发布于 2015-08-03 18:23:57
检查我的实现@ http://mpand.github.io/gnp/
以JSON对象的形式返回故事和URL
https://stackoverflow.com/questions/31778504
复制相似问题