用python写网络爬虫

识别网站所用技术

  1. 安装模块

    pip install builtwith

  2. 进行分析

python 复制代码
>>> import builtwith
>>> builtwith.parse('http://www.baidu.com')
{'javascript-frameworks': ['Prototype', 'RequireJS', 'jQuery']}

寻找网站所有者

有些网站所有者会封禁网络爬虫 所以需要控制下载速度,可以使用WHOIS协议查询域名的注册者

python-whois · PyPI

通过命令行下载

python 复制代码
pip install python-whois

执行

python 复制代码
>>> import whois
>>> print whois.whois('baidu.com')

编写第一个网络爬虫

1. 下载网页

要想爬取一个网页,首先要将其下载下来

py2写法:

python 复制代码
import urllib2

def download(url) :
  
    return urllib2.urlopen(url).read()

py3写法

python 复制代码
import urllib.request

# 发起请求
response = urllib.request.urlopen("https://www.baidu.com")
data = response.read()

# 保存到文件
with open("output.html", "wb") as f:
    f.write(data)

2. 设置用户代理

在 Python 3 中,使用 urllib.request 模块发送 HTTP 请求时,默认的用户代理(User-Agent)是 Python-urllib/3.x(其中 x 是你使用的 Python 3 的具体版本号)。

例如,如果你使用 Python 3.8,默认的用户代理字符串可能是 Python-urllib/3.8。

这个默认用户代理在某些网站上可能会被识别为爬虫并被拒绝访问。如果你需要模拟浏览器行为,通常需要自定义用户代理,例如:

python 复制代码
import urllib.request

url = "https://www.baidu.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'
}

req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
content = response.read()

上面代码示例中设置的用户代理(User-Agent)是:

python 复制代码
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

这个用户代理字符串表示的是 Windows 10 操作系统上的 Chrome 91 浏览器。这种用户代理是非常典型的现代浏览器标识,通常用于模拟真实的浏览器访问,以避免被网站识别为爬虫或自动化程序而被拒绝访问。

相关推荐
默_笙14 小时前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!14 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_4260039614 小时前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫14 小时前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技14 小时前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读15 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时15 小时前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车16 小时前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊16 小时前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd12316 小时前
2026年第38周GitHub趋势周报
python·科技·github