本文介绍了f'https://google.com/search?q = {query}'中的soup.select('.r a')带回Python BeautifulSoup中的空列表. **不重复**的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很幸运!" 使用Python自动处理无聊的东西"电子书中的项目不再适用于他提供的代码.

The "I'm Feeling Lucky!" project in the "Automate the boring stuff with Python" ebook no longer works with the code he provided.

具体来说,linkElems = soup.select('.r a')

Specifically, the linkElems = soup.select('.r a')

我已经尝试使用以下提供的解决方案: soup.select('. "https://www.google.com/#q=vigilante+mic"中的"r a")在python BeautifulSoup中给出了空列表

I've already tried using the solution provided in:soup.select('.r a') in 'https://www.google.com/#q=vigilante+mic' gives empty list in python BeautifulSoup

,并且我目前使用的是相同的搜索格式.

, and I'm currently using the same search format.

import webbrowser, requests, bs4

def im_feeling_lucky():

    # Make search query look like Google's
    search = '+'.join(input('Search Google: ').split(" "))

    # Pull html from Google
    print('Googling...') # display text while downloading the Google page
    res = requests.get(f'https://google.com/search?q={search}&oq={search}')
    res.raise_for_status()

    # Retrieve top search result link
    soup = bs4.BeautifulSoup(res.text, features='lxml')


    # Open a browser tab for each result.
    linkElems = soup.select('.r')  # Returns empty list
    numOpen = min(5, len(linkElems))
    print('Before for loop')
    for i in range(numOpen):
        webbrowser.open(f'http://google.com{linkElems[i].get("href")}')

linkElems变量返回一个空列表[],程序不执行任何操作.

The linkElems variable returns an empty list [] and the program doesn't do anything past that.

推荐答案

我在读那本书时也遇到了同样的问题,并找到了解决该问题的方法.

I too had had the same problem while reading that book and found a solution for that problem.

替换

soup.select('.r a')

soup.select('div#main > div > div > div > a')

将解决该问题

以下是将起作用的代码

import webbrowser, requests, bs4 , sys

print('Googling...')
res = requests.get('https://google.com/search?q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text)

linkElems = soup.select('div#main > div > div > div > a')
numOpen = min(5, len(linkElems))
for i in range(numOpen):
    webbrowser.open('http://google.com' + linkElems[i].get("href"))

上面的代码从命令行参数中获取输入

the above code takes input from commandline arguments

这篇关于f'https://google.com/search?q = {query}'中的soup.select('.r a')带回Python BeautifulSoup中的空列表. **不重复**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:05