Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于打印包含特定单词的web链接的Python程序不会输出任何内容_Python_Http_Beautifulsoup_Web Crawler_Html Parsing - Fatal编程技术网

用于打印包含特定单词的web链接的Python程序不会输出任何内容

用于打印包含特定单词的web链接的Python程序不会输出任何内容,python,http,beautifulsoup,web-crawler,html-parsing,Python,Http,Beautifulsoup,Web Crawler,Html Parsing,我想打印出包含特定关键字的新闻文章的网络链接,比如特斯拉。因此,我在谷歌新闻主页上搜索了tesla这个词,我编写了以下代码来搜索包含tesla这个词的文章,这应该是所有的文章,因为它在一系列包含该词的文章中搜索该词: import httplib2 from bs4 import BeautifulSoup, SoupStrainer http = httplib2.Http() status, response = http.request('https://news.google.com/

我想打印出包含特定关键字的新闻文章的网络链接,比如特斯拉。因此,我在谷歌新闻主页上搜索了tesla这个词,我编写了以下代码来搜索包含tesla这个词的文章,这应该是所有的文章,因为它在一系列包含该词的文章中搜索该词:

import httplib2
from bs4 import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('https://news.google.com/search?q=tesla&hl=en-US&gl=US&ceid=US%3Aen')

words_to_search = ['tesla']

for link in BeautifulSoup(response, "lxml", parse_only=SoupStrainer('a')):
    if 'href' in link:
        for word in words_to_search:
            if word in link['href']:
                print(link['href'])

但我没有得到输出或是空输出。为什么代码无法找到具有指定单词的文章?我该如何修复它呢?

当您调用link[href]时,您正在提取文章的URL,其中可能不包含Tesla一词。您可能希望执行以下操作:

resp, content = http.request(link['href'], "GET") 
获取页面的实际内容,这些内容将存储在内容中

此外,您在示例中的示例搜索链接是在谷歌新闻中搜索“保险”一词,因此,如果这是您真正使用的链接,您可能不会在其中搜索包含特斯拉的文章

因此,link['href']是URL,而不是文章本身。URL可能都是小写的,所以它可能包含tesla,而不是tesla。您需要进行另一个API调用来获取文章文本本身。