f'https://google.com/search?q = {query}'中的soup.select('。r a')带回PythonBeautifulSoup中的

【字号: 日期:2022-09-29浏览:25作者:雯心
如何解决f'https://google.com/search?q = {query}'中的soup.select('。r a')带回PythonBeautifulSoup中的空列表。**不重复**?

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

更换

soup.select(’.r a’)

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

将解决这个问题

以下是将起作用的代码

import webbrowser, requests, bs4 , sysprint(’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'))

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

解决方法

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

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

我已经尝试使用提供的解决方案: “ https://www.google.com/#q=vigilante+mic”中的soup.select(’。ra’)在pythonBeautifulSoup中提供了空列表

,而我目前正在使用相同的搜索格式。

import webbrowser,requests,bs4def 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变量返回一个空列表[],程序不执行任何操作。

标签: Python 编程
相关文章: