【问题标题】:Selenium get() redirects to another urlSelenium get() 重定向到另一个 url
【发布时间】:2021-05-05 14:30:05
【问题描述】:

我正在尝试导航到以下页面并提取 html https://www.automobile.it/annunci?b=data&d=DESC,但每次我调用 get() 方法时,看起来网站都会将我重定向到另一个页面,始终是相同的页面,即 @987654322 @。

这是我正在运行的简单代码:

from selenium import webdriver
driver = webdriver.Chrome(executable_path=ex_path)
driver.get("https://www.automobile.it/annunci?b=data&d=DESC")
html=driver.page_source

如果我使用请求模块做同样的事情,我不会被重定向

import requests
html=requests.get("https://www.automobile.it/annunci?b=data&d=DESC")

我不明白它为什么会这样,有什么想法吗?

【问题讨论】:

  • 听起来 cookie 正在影响您的抓取。

标签: python selenium web-scraping


【解决方案1】:

使用driver.delete_all_cookies()

from selenium import webdriver
driver = webdriver.Chrome(executable_path=ex_path)
driver.delete_all_cookies()
driver.get("https://www.automobile.it/annunci?b=data&d=DESC")
html=driver.page_source

PS:另外请注意:Page_source 不会为您提供渲染完成的 DOM。

【讨论】:

  • driver.delete_all_cookies() 行为更改为 URL-->redirect URL2-->redirect URL,它仍然通过重定向但它返回到正确的 URL,我想知道你是否有任何想法为什么会发生这种情况,我想进行更多测试,但恐怕这种解决方法可能不稳定。此外,我只发布了完整代码的 sn-p,然后将 html 传递给 BeautifulSoup 以进一步处理它,我唯一需要的是 html=driver.page_source 返回与 requests.get 相同的 html
  • requests.get 可能没有处理重定向。什么是状态码?
  • 重定向可能是 SUT 的正确操作。我无法验证他们的结果。
  • 对不起,我没有注意到我重复了相同的命令,这就是它执行 URL-->URL2-->URL 的原因,如果我只保留您的代码行,它就不起作用打算它仍然重定向到 URL2。 request.get() 的状态码是 200。什么是 SUT?我试图谷歌它,但找不到意思。我真的需要找到一种方法来避免重定向到网站的其他部分......
【解决方案2】:

您可以使用以下代码清除浏览器缓存:

我假设您使用的是 chrome。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path=ex_path)
driver.get('chrome://settings/clearBrowserData')
driver.find_element_by_xpath('//settings-ui').send_keys(Keys.ENTER)
driver.get("https://www.automobile.it/annunci?b=data&d=DESC")

【讨论】:

  • 它抛出以下错误:selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable我必须明确设置等待如下from selenium.webdriver.common.action_chains import ActionChainsbutton = driver.find_element_by_xpath("//settings-ui")driver.implicitly_wait(10)ActionChains(driver).move_to_element(button).click(button).perform()我仍然被重定向到第二个 URL
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 2013-05-28
  • 2020-09-05
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多