欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

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

2025年07月29日 Python
使用requests库模拟浏览器请求requests 是一个简单易用的 http 库,可以模拟浏览器的请求行为。通常需要设置请求头和 cookies 来伪装成浏览器。import requestsur

使用requests库模拟浏览器请求

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

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

import requests

url = "https://example.com"
headers = {
    "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",
    "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进行高级浏览器模拟

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

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(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 by
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_located((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)

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。