如何在Python中将数据从括号和花括号中提取出来?

3

我正在尝试使用py-web-search模块从谷歌搜索中提取信息。提取搜索结果的结果如下(如Github所述):

{
    'url': '...',
    'expected_num': 5,
    'received_num' : 5, # There will be a difference in case of insufficient results
    'start': 2,
    'search_engine': 'google',
    'total_results': ...,
    'results':
    [
        {
            'link': '...',
            'link_text': '...',
            'link_info': '...',
            'related_queries': [...],
            'additional_links':
            {
                linktext: link,
                ...
            }
        },
        ...
    ]
}

我似乎无法找出如何将“链接(link)”数据打印出来。

result=Google.search(query='hello world', num=5, start=0, country_code="es")
data=result['results']
print(data)

这是我的测试代码,只打印[]。有什么建议吗?

1
列表(方括号)仅由数字索引,从0开始。字典(花括号)通常通过点符号或方括号进行索引,但使用字符串。这有帮助吗? - OneCricketeer
1
看起来你的尝试是可以的,但我建议尝试打印结果变量,以查看字典中的结果条目是否实际包含任何结果。 - LhasaDad
数据以JSON格式存储。使用Python中的JSON模块提取数据或将数据转储到字典中。 - Akash Lodha
1
那不是 JSON,这是 Python 字典。 - jDo
这明显不是JSON,因为它有单引号;JSON在这方面非常严格,只接受双引号。 - Daniel Roseman
1个回答

6
您所做的是正确的,但那个库已经过时了,并且在Google搜索中不返回任何结果。有关详细信息,请参见此问题

此外,Google已更改HTML结构。因此,必须更新网络爬虫。感谢报告错误!

作为临时解决方案,您可以考虑使用Bing作为您的搜索引擎,因为它仍然可以工作:
from pws import Bing
result = Bing.search('hello world', 5, 2)
print(result["results"])

1
刚测试了一下,我看到的正是这样。{'search_engine': 'google', 'received_num': 0, 'expected_num': 10, 'country_code': None, 'start': 0, 'url': 'https://www.google.com/search?q=hello+world&num=10&start=0', 'related_queries': ['hello world lyrics', 'hello world html', 'hello world song', 'hello world python', 'hello world java', 'hello world book', 'hello world c++', 'hello world tutorial'], 'total_results': 35100000, 'results': []} - J.B
1
@J.B 没错,results 列表是空的。 - Selcuk
谢谢大家。我以为我在做错什么了。您知道有哪些库适用于这个目的吗? - Lionspridde
是的,请尝试查看此源文件(第119行),其中结果被解析为: raw_results = soup.find_all('li', attrs = {'class' : 'g'})。换句话说,它基于“li”标签,但是如果您查看Google结果的HTML代码,那里没有li标签。 - Eduard Stepanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接