【问题标题】:How do I obtain redirected URLs?如何获取重定向的 URL?
【发布时间】:2021-06-11 04:04:02
【问题描述】:

我正在尝试获取 https://trade.ec.europa.eu/doclib/html/153814.htm 指向的重定向 URL(一个 pdf 文件)。

我已经试过了

r = requests.get('https://trade.ec.europa.eu/doclib/html/153814.htm', allow_redirects = True)
print(r.url) 

它会输出相同的旧 URL。我需要重定向的 URL,即https://trade.ec.europa.eu/doclib/docs/2015/september/tradoc_153814.pdf

【问题讨论】:

标签: python web-scraping python-requests


【解决方案1】:

请尝试此代码,看看它是否适合您

import urllib.request
import re
import requests
import PyPDF2
import io
from requests_html import HTMLSession
from urllib.parse import urlparse
from PyPDF2 import PdfFileReader
 
# Get Domain Name With urlparse
url = "https://trade.ec.europa.eu/doclib/html/153814.htm"
parsed_url = urlparse(url)
domain = parsed_url.scheme + "://" + parsed_url.netloc
 
# Get URL 
session = HTMLSession()
r = session.get(url)
 
# Extract Links
jlinks = r.html.xpath('//a/@href')
 
# Remove bad links and replace relative path for absolute path
updated_links = []
 
for link in jlinks:
    if re.search(".*@.*|.*javascript:.*|.*tel:.*",link):
        link = ""
    elif re.search("^(?!http).*",link):
        link = domain + link
        updated_links.append(link)
    else:
        updated_links.append(link)
r = requests.get(updated_links[0])
f = io.BytesIO(r.content)
reader = PdfFileReader(f)
contents = reader.getPage(0).extractText() 
print(contents)

【讨论】:

  • 这将是我的下一个查询。感谢您帮助我获取文档内容。
  • 但是你点击了投票按钮下的勾号以获得另一个回复;)
【解决方案2】:

我认为您应该自己获得一个重定向链接(没有找到任何使用重定向的方法),当您输入 https://trade.ec.europa.eu/doclib/html/153814.htm 时,它会为您提供带有重定向链接的 HTML 页面,例如,您可以像这样提取它这个

import requests
from lxml import etree, html

tree = html.fromstring(requests.get('https://trade.ec.europa.eu/doclib/html/153814.htm').text)
print(tree.xpath('.//a/@href')[0])

输出将是

https://trade.ec.europa.eu/doclib/docs/2015/september/tradoc_153814.pdf

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 2018-05-02
    • 1970-01-01
    • 2013-07-20
    • 2016-12-22
    • 2016-12-11
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多