【问题标题】:How to get the redirected URL in Web Scraping?如何在 Web Scraping 中获取重定向的 URL?
【发布时间】:2020-03-07 09:14:25
【问题描述】:

我想要的只是请求实际 url 后的重定向 url。这是实际的 url https://metric.picodi.net/us/r/19761,当我使用这个 url 在浏览器上按 Enter 键时,它会将我重定向到这样的 url

https://www.overstock.com/?AID=11557584&PID=9096967&SID=5e479aea42dd4d2c85183aa2&cjevent=2e4090483d7d3c3db27e63d14903c327c7718b978cf0dfa24&entrytrigger=noshow&exittrigger=noshow&fp=F&utm_source=cj&utm_medium=affiliates

我试图像这样实现它,但它给了我相同的 url

>>> import requests
>>> r = requests.get('https://metric.picodi.net/us/r/19761', allow_redirects=True)
>>> print(r.url)
https://metric.picodi.net/us/r/19761
>>> r.history
[]

我也尝试了以下 -

>>> r = requests.head('https://metric.picodi.net/us/r/19761', allow_redirects=True)
>>> print(r.url)
https://metric.picodi.net/us/r/19761
>>> r.history
[]

【问题讨论】:

  • 检查您在r.text 中获得的内容 - 可能有机器人警告,您可能需要使用标题User-Agent 来假装真正的网络浏览器。或者有 JavaScript 代码重定向到其他页面 - requests 无法执行 JavaScript 但您可以尝试从 JavaScript 获取 url 并手动运行请求。
  • @furas 我们需要看看如何即时渲染GET/HEAD 请求。因为我完全确定这可以即时完成。

标签: python web-scraping beautifulsoup scrapy


【解决方案1】:

这是由于JavaScript 在页面加载后动态处理重定向。

因此,您可以使用Selenium 实现这一目标

类似于以下内容:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.add_argument('--headless')
driver = webdriver.Firefox(options=options)
link = 'https://metric.picodi.net/us/r/19761'

driver.get(link)
print(driver.current_url)

driver.quit()

输出:

https://www.overstock.com/?AID=11557584&PID=9096967&SID=5e63c10642dd4d26f7549875&cjevent=121071440d708c3db27e63d55903c327c7718b9633548769c&entrytrigger=noshow&exittrigger=noshow&fp=F&utm_source=cj&utm_medium=affiliates

请注意,您可能会使用requests_html,这将是为您呈现JavaScript 的好朋友。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多