f'https://google.com/search?q = {query}'中的soup.select('。r a')帶回PythonBeautifulSoup中的
我在讀那本書(shū)時(shí)也遇到了同樣的問(wèn)題,并找到了解決該問(wèn)題的方法。
更換
soup.select(’.r a’)
與
soup.select(’div#main > div > div > div > a’)
將解決這個(gè)問(wèn)題
以下是將起作用的代碼
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'))
上面的代碼從命令行參數(shù)獲取輸入
解決方法“我很幸運(yùn)!” 電子書(shū)“使用Python自動(dòng)處理無(wú)聊的東西”中的項(xiàng)目不再適用于他提供的代碼。
具體來(lái)說(shuō),linkElems = soup.select(’。r a’)
我已經(jīng)嘗試使用提供的解決方案: “ 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變量返回一個(gè)空列表[],程序不執(zhí)行任何操作。
