Python爬虫:设置随机 User-Agent

Python爬虫:设置随机 User-Agent

在Python中编写爬虫时,为了模拟真实用户的行为并防止被服务器识别为爬虫,通常需要设置随机的User-Agent。你可以使用fake-useragent库来实现这一功能。首先,你需要安装fake-useragent库:

复制代码
pip install fake-useragent

然后,你可以按照以下示例代码来设置随机User-Agent:

复制代码
import requests
from fake_useragent import UserAgent
def get_random_user_agent():
    ua = UserAgent()
    return ua.random
def crawl_url(url):
    headers = {'User-Agent': get_random_user_agent()}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.text
    else:
        print("Failed to fetch URL:", response.status_code)
if __name__ == "__main__":
    url = "https://example.com"  # 要爬取的网址
    html_content = crawl_url(url)
    print(html_content)  # 输出网页内容

编辑

这个示例中,get_random_user_agent() 函数使用fake-useragent库来获取一个随机的User-Agent字符串,并将其用于构造请求头。然后,crawl_url() 函数发送带有随机User-Agent的HTTP请求,并返回网页内容。

记得在使用爬虫时,要尊重网站的robots.txt文件,以避免访问被禁止的页面。同时,避免发送过于频繁的请求,以免对服务器造成负担。

相关推荐
zone773914 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant14 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来15 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_15 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend16 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽16 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python