Requests.get()函数的结果与webbrowser.open()函数的结果不同

我有一个需要运行的URL才能进行刷新。它将刷新数据缓存并在Tableau Server中显示最新上传的数据。网址是这样的:

http://servername/views/workbookname/dashboard1?:refresh=yes

当我使用webbrowser库打开url时,将执行刷新,但是会得到一个打开的浏览器。当我使用请求获取url时,它不会刷新并给我200的响应,我认为这是成功的。

有人知道为什么会发生吗?如何在执行get函数时以静默方式使用webbrowser库打开URL并随后将其关闭,或者让请求充当webbrowser?

import webbrowser
url = 'http://servername/views/workbookname/dashboard1?:refresh=yes'
webbrowser.open(url)

import requests
url = "http://servername/views/workbookname/dashboard1?:refresh=yes"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/56.0.2924.76 Safari/537.36',"Upgrade-Insecure-Requests": "1","DNT": "1","accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","accept-Language": "en-US,en;q=0.5","accept-Encoding": "gzip,deflate"}
html = requests.get(url,headers=headers)
print(html)
ranjing9 回答:Requests.get()函数的结果与webbrowser.open()函数的结果不同

打开浏览器的原因仅仅是因为webbrowser.open()应该这样做,而不是发送HTTP请求,而是打开浏览器并输入URL。一种可能的解决方案是使用硒而不是webbrowser,因为当我看着它时,我还没有找到您正在使用的软件包的无用选项。所以这里是:

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

url = "<URL>"

chrome_options = Options()  
chrome_options.add_argument("--headless")

with Chrome(options=chrome_options) as browser:
     browser.get(url)

如果此解决方案不可接受,因为您需要使用Webdriver而不是Selenium,则需要找到一种将选项传递给浏览器实例的方法。我没有找到用dir()或help()将该参数传递给webbrowser的方法,但是如果我发现了一些东西,我会添加它。

,

requests.get()仅在“ GET”请求之后返回从服务器收到的标记,而无需任何进一步的客户端执行。

在浏览器上下文中,可以在客户端javascript上做更多的事情。我没有专门查看您的页面,但可能会有某些javascript代码进行进一步处理。

可以使用Selenium代替web browserrequests。您可以详细了解here

Selenium使您可以像使用浏览器一样浏览器页面,但是还可以灵活地使用python代码自动执行+控制页面上的操作。

您也许可以使用Selenium Chrome Webdriver在后台加载页面。 (或者您可以使用Firefox驱动程序。)

转到chrome://settings/help检查当前的Chrome版本,然后从here下载该版本的驱动程序。确保将驱动程序文件保存在PATH或python脚本所在的文件夹中。

尝试一下:

from selenium.webdriver import Chrome # pip install selenium
from selenium.webdriver.chrome.options import Options

url = "http://servername/views/workbookname/dashboard1?:refresh=yes"

#Make it headless i.e. run in backgroud without opening chrome window
chrome_options = Options()  
chrome_options.add_argument("--headless")

# use Chrome to get page with javascript generated content
with Chrome(executable_path="./chromedriver",options=chrome_options) as browser:
     browser.get(url)
     page_source = browser.page_source

注意

当您打开URL时,webbrowser模块将启动默认浏览器,该浏览器已经缓存了您的凭据/ cookie。而如果您的URL需要任何身份验证或登录名才能访问,则在使用硒获取页面时必须提供这些信息。将每个硒Web驱动程序会话视为隐身会话。 Here是有关如何使用Web驱动程序模拟登录的示例。


参考文献:

selenium - chromedriver executable needs to be in PATH

本文链接:https://www.f2er.com/3156432.html

大家都在问