使用Python Selenium cookies和请求从PDF查看器下载PDF

2024-09-28 19:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Selenium很熟悉,对请求不熟悉。此网页包含公共PDF,但您必须导航到每个PDF。所以我想要的是使用Selenium导航到该url,然后在请求中使用cookies下载PDF

然后我将把这个解决方案上传到AWS lambda,所以点击下载按钮不是一个选项(也不是使用“plugins.always\u open\u pdf\u externally”:True-in-chrome选项)。 以下是我迄今为止所做的尝试:

我按照以下说明导航到selenium的PDF(不会包含代码,因为它很长很简单,但我可以确认我在PDF查看器页面中),然后:

url = driver.current_url
cookies = driver.get_cookies()
s = requests.Session()
for cookie in cookies:
    if 'httpOnly' in cookie:
        httpO = cookie.pop('httpOnly')
        cookie['rest'] = {'httpOnly': httpO}
    if 'expiry' in cookie:
        cookie['expires'] = cookie.pop('expiry')
    s.cookies.set(**cookie)
filename = Path('myPDF.pdf')
response = s.get(url)
filename2.write_bytes(response.content)
print(response)
OUT: <Response [404]>
print(cookies)
OUT: [{'domain': '.pjud.cl', 'expiry': 1677609957, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.184425928.1614537957'}, {'domain': '.pjud.cl', 'expiry': 1614624357, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.739803934.1614537957'}, {'domain': '.oficinajudicialvirtual.pjud.cl', 'httpOnly': False, 'name': 'TS01262d1d', 'path': '/', 'secure': False, 'value': '01b485afe5b672a4e38a46b7a3a68bf7abce5fe06744257fa0f994999756bd24588a29453de9650e8fdfe73a401e5d854fe3c382a3b4a0677cbbe7d18acd3bc46c00faebd1'}, {'domain': '.pjud.cl', 'expiry': 1614538017, 'httpOnly': False, 'name': '_gat_gtag_UA_63880126_1', 'path': '/', 'secure': False, 'value': '1'}, {'domain': 'oficinajudicialvirtual.pjud.cl', 'httpOnly': False, 'name': 'PHPSESSID', 'path': '/', 'secure': False, 'value': '6f9a7ee252846eeb63a6cc2233dacf21'}]
print(s.cookies)
OUT: <RequestsCookieJar[<Cookie TS01262d1d=01b485afe5b672a4e38a46b7a3a68bf7abce5fe06744257fa0f994999756bd24588a29453de9650e8fdfe73a401e5d854fe3c382a3b4a0677cbbe7d18acd3bc46c00faebd1 for .oficinajudicialvirtual.pjud.cl/>, <Cookie _ga=GA1.2.184425928.1614537957 for .pjud.cl/>, <Cookie _gat_gtag_UA_63880126_1=1 for .pjud.cl/>, <Cookie _gid=GA1.2.739803934.1614537957 for .pjud.cl/>, <Cookie PHPSESSID=6f9a7ee252846eeb63a6cc2233dacf21 for oficinajudicialvirtual.pjud.cl/>]>

Here's an example of a url.

它会告诉您会话已过期,但您可以按照下面的说明进行操作。 请注意,它是一个pdf查看器,并且不会以.pdf结尾(不知道这是否有区别)

要达到目标,您必须:

  1. 进入https://oficinajudicialvirtual.pjud.cl/home/index.php
  2. 悬停在“Otros Servicios”上方
  3. 点击“原因咨询”
  4. 在“Competencia”(下拉菜单)中,放置Corte Apelacions
  5. 在“Corte”(下拉菜单)中,放置CA Santiago
  6. 在“Año”输入中
  7. 在“Libro/Tipo”(下拉菜单)中,输入Civil
  8. 在“Rol”输入2522中(所有这些都是我想要刮取的)
  9. 单击“客车”
  10. 只显示一个结果,单击左侧的放大镜
  11. 弹出详细信息,点击“便利Primera Instancia”
  12. 单击“Causa Origen”旁边的放大镜
  13. 单击“Texto/demanda”下面的文件图标。pdf将在pdf查看器中的新选项卡中打开

创建的PDF为空,响应返回<;响应[404]>;。帮助 我需要向请求添加标题吗?我不知道怎么做,谢谢


Tags: pathnamefalseurlforpdfclcookie