Atu*_*aon 17 web-scraping python-3.x puppeteer playwright-python
我希望连接到网站并下载一些 pdf 文件。该网站允许我们只有登录后才能查看内容。它要求我们使用OTP登录,并且不能同时在超过3台设备上登录。
我想下载列出的所有 pdf 文件。所以我之前尝试过
python playwright open --save-storage websitename.json
Run Code Online (Sandbox Code Playgroud)
保存登录信息。但它不适用于该特定网站。website.json 文件是空的,但它适用于其他网站。
因此,我能想到的唯一解决方案是连接到当前的浏览器,打开该网站,然后下载这些 pdf。
如果您对此有解决方案,甚至有其他方法,请告知。
我也在考虑转行做木偶师。但是,我不知道使用node.js解析html,因为我觉得使用css选择器更舒服,所以我无法切换它。
ePa*_*dit 14
要连接到已运行的浏览器 (Chrome) 会话,您可以使用connect_over_cdp方法(在 playwright v1.9 中添加)。
为此,您需要以调试模式启动 Chrome。为 Chrome 创建桌面快捷方式并编辑快捷方式属性的目标部分以使用调试模式启动它。添加--remote-debugging-port=9222到快捷方式属性中的目标框中,使目标路径变为:
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
现在启动 Chrome 并检查它是否处于调试模式。为此,打开一个新选项卡并将此网址粘贴到地址栏中:http://localhost:9222/json/version。如果您处于调试模式,您现在应该看到一个带有 json 响应的页面,否则,如果您处于“正常”模式,它会显示“找不到页面”或类似的内容。
现在,在您的 python 脚本中,编写以下代码来连接到 chrome 实例:
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
default_context = browser.contexts[0]
page = default_context.pages[0]
Run Code Online (Sandbox Code Playgroud)
这是完整的脚本代码:
# Import the sync_playwright function from the sync_api module of Playwright.
from playwright.sync_api import sync_playwright
# Start a new session with Playwright using the sync_playwright function.
with sync_playwright() as playwright:
# Connect to an existing instance of Chrome using the connect_over_cdp method.
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
# Retrieve the first context of the browser.
default_context = browser.contexts[0]
# Retrieve the first page in the context.
page = default_context.pages[0]
# Print the title of the page.
print(page.title())
# Print the URL of the page.
print(page.url)
Run Code Online (Sandbox Code Playgroud)
剧作家与木偶师基本相同。所以如果你在两者之间切换的话,就不会有问题。
您可以使用puppeteer-core或playwright来控制您现有的浏览器安装,例如 Chrome,然后使用现有的用户数据(Profile)文件夹加载指定的网站登录信息(cookie、webstorage 等)。
const launchOptions = {
headless: false,
executablePath: '/Applications/Google Chrome/Contents/MacOS/Google Chrome', // For MacOS
// executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', // For Windows
// executablePath: '/usr/bin/google-chrome' // For Linux
args: [
'--user-data-dir=/Users/username/Library/Application Support/Google/Chrome/', // For MacOS
// '--user-data-dir=%userprofile%\\AppData\\Local\\Chrome\\User Data', // For Windows
// '--profile-directory=Profile 1' // This to select default or specified Profile
]
}
const puppeteer = require('puppeteer-core')
const browser = await puppeteer.launch(launchOptions)
Run Code Online (Sandbox Code Playgroud)
有关 Playwright 方法的更多详细信息,您可以查看此解决方法: https: //github.com/microsoft/playwright/issues/1985
| 归档时间: |
|
| 查看次数: |
13915 次 |
| 最近记录: |