python - 如何修复此打开网络浏览器的代码?
问题描述
我是 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 操作系统上运行它。
谢谢你帮助我:)
解决方案
替换以下行 -
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 会在新选项卡中打开新网页。
推荐阅读
- android - 我可以将非主键字段作为房间中的自动生成值吗
- intellij-idea - Intellij IDEA 运行配置系统环境与操作系统环境不匹配
- javascript - 加载后AngularJS可以编译由外部库附加的HTML吗?
- java - 如何处理任何 TCP 传入连接?所有端口或端口范围
- html - 调整屏幕大小时徽标居中问题
- c++ - 每次在文件中写入时,如何在前面附加文本?
- c# - 如何将类对象列表添加到类中?
- c# - c# utf-8 与德语变音符号的转换问题
- pdf - Saxon / Fop / PDF 在 Chrome/Edge 中有奇怪的粗线,但在 Firefox / Safari 中没有
- ios - 如果在通话期间网络从 IPv6 切换到 IPv4,则 pjsip 通话挂断延迟