首页 > 解决方案 > 如何修复此打开网络浏览器的代码?

问题描述

我是 Python 的新手,正在尝试学习这种美妙的网络爬虫语言。

我编写了一个非常简单的程序来学习如何使用 requests 模块和 BeautifulSoup 模块。

该程序应该在新窗口中打开谷歌搜索的五个第一个结果。搜索的关键词被写为参数。

# lucky.py - Opens several Google search results.

import webbrowser, bs4, requests, sys

print('Googling...') # display text while downloading the Google page
res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()

# Retrieve top search result links.
soup = bs4.BeautifulSoup(res.text, "lxml")

# Open a browser tab for each result
link_elems = soup.select('.r a')
num_open = min(5, len(linkElems))
for i in range(num_open):
    webbrowser.open('http://google.com' + link_elems[i].get('href'))

当我在终端中启动程序时,它会显示一个带有文本“谷歌搜索...”的终端窗口,但它会关闭并且没有打开任何网络浏览器窗口。

为了解决这个问题,我尝试使用 urllib.request :urllib.request.urlopen('http://google.com/search?q=' + ' '.join(sys.argv[1:])).read()

我还添加了 lxlm :soup = bs4.BeautifulSoup(res.text, "lxml")因为建议使用它。

该程序仍然无法运行,我有点困惑......我在 Miscrosoft Windows 操作系统上运行它。

谢谢你帮助我:)

标签: pythonweb-scraping

解决方案


替换以下行 -

webbrowser.open(' http://google.com ' + link_elems[i].get('href'))

用这两行代码-

chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s' webbrowser.get(chrome_path).open(' http://google.com ' + link_elems[i].get( 'href'))

如果这不起作用,请尝试向 webbrowser.get 提供“新”参数,例如 -

webbrowser.open(网址,新 = 2)

如果可能,提供新的 1 会在新窗口中打开网页,如果可能,提供 2 会在新选项卡中打开新网页。


推荐阅读