php - 如何让 Python3 网页抓取程序处理本地 cookie?
问题描述
我试图编写一个可以自动下载文件的程序(带有php链接)。但是,我现在有两个问题
首先,我的目标网站需要注册才能首次访问。然后,每次我点击下载链接时,它都会自动下载我想要的文件。看起来像是搜索了一些保存在我电脑上的 cookie 以确定我是谁。如何让我的 python 程序处理我的本地 cookie?如果是倍数?
其次,谁能给我一个关于如何处理php下载链接文件的示例代码?我想以特定名称将所有这些文件保存在特定位置。我应该如何在python3中做到这一点?
解决方案
获取 cookie:
尝试:
import urllib.request
cookier = urllib.request.HTTPCookieProcessor()
# create the cookie handler
opener = urllib.request.build_opener(cookier)
urllib.request.install_opener(opener)
将HTTPCookieProcessor
返回cookielib.CookieJar
包含这些 cookie 的对象。您可以遍历它以找到您想要的cookie。
for c in cookier.cookiejar:
if c.domain == '.stackoverflow.com':
# do something
阅读链接中的内容:
尝试:
url = 'YOUR_URL'
req = urllib.request.Request(url, headers=_headers) # where headers is the header setting you can find in your brwoser
f = urllib.request.urlopen(req)
contents = f.read().decode('utf-8')
# contents is the content inside your file
# You can add the code here to write contents to other file to save it
推荐阅读
- javascript - 尝试使用 react-image-gallery 时出现“无法加载图像”错误,即使文件路径绝对正确
- python - 使用已知目标函数实现梯度下降
- github - 如何在 Sphinx 的 conf.py 中访问 Git Commit ID
- python-3.x - pd.to_datetime 输出为 1970-01-01 00:00:00.0000
- python - python的元音计数代码分解
- php - 在 n1 页面中调用单独的 AJAX 函数的多个按钮
- sql - 如何根据从另一个表中选择的结果更新一个表中的列
- java-8 - Java 8 POJO 对象基于常用的多个键组合过滤 pojo 并在一个字段上求和
- python - Python - 如何替换多个输出行?
- python - 如何将两个数据框放在另一个上并保留所有不同的值?