当前位置: 代码网 > it编程>前端脚本>Python > python运用requests模拟浏览器发送请求过程

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)

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

总结

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com