开发者

python运用requests模拟浏览器发送请求过程

目录
  • 使用requests库模拟浏览器请求
  • 使用selenium自动化浏览器操作
  • 使用playwright进行高级浏览器模拟
  • 设置代理和超时
  • 处理动态加载内容
  • 模拟表单提交
  • 总结

使用requests库模拟浏览器请求

requests 是一个简单易用的 HTTP 库,可以模拟浏览器的请求行为。

通常需要设置请求头和 Cookies 来伪装成浏览器。

import requests

url = "https://example.com"
headers = {
    "User-Agent": "Mozilla/5.0 (WindPqGzbcNzUiows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Accept": "text/html,application/Xhtml+XML,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
}
cookies = {"session_id": "123456789"}

response = requests.get(url, headers=headers, cookies=cookies)
print(response.text)

使用selenium自动化浏览器操作

selenium 可以控制真实浏览器(如 Chrome、Firefox)进行自动化操作,适合需要执行 JavaScript 或处理动态内容的场景。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://example.com")
print(driver.page_source)
driver.quit()

使用playwright进javascript行高级浏览器模拟

playwright 是一个现代浏览器自动化工具,支持 Chromium、Firefox 和 WebKit,提供了更强大的功能。

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.phplaunch(headless=False)  # 非无头模式
    page = browser.new_page()
    page.goto("https://example.com")
    print(page.content())
    browser.close()

设置代理和超时

如果需要通过代理发送请求或控制超时时间,可以在请求中添加相关参数。

proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080",
}
timeout = 10  # 超时时间(秒)

response = requests.get(url, headers=headers, proxies=proxies, timeout=timeout)

处理动态加载内容

某些网站通过 javascript 动态加载内容,可以使用 seleniumplaywright 等待元素加载完成。

from selenium.webdriver.common.by import PqGzbcNzUiBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver.get("https://example.com")
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_lojscated((By.ID, "dynamic-content"))
)
print(element.text)

模拟表单提交

如果需要提交表单数据,可以使用 requests 发送 POST 请求。

data = {
    "username": "test",
    "password": "123456",
}
response = requests.post(url, data=data, headers=headers)
print(response.text)

通过以上方法,可以模拟浏览器发送请求并获取响应内容。根据实际需求选择合适的工具和技术方案。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜