用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 浏览器。这种用户代理是非常典型的现代浏览器标识,通常用于模拟真实的浏览器访问,以避免被网站识别为爬虫或自动化程序而被拒绝访问。

相关推荐
残轩5 分钟前
是时候考虑用uv管理你的python项目及依赖了
python·rust
独行soc7 分钟前
2025年渗透测试面试题总结-某快手-安全工程师(题目+回答)
网络·数据库·python·安全·面试·职场和发展·红蓝攻防
赴前尘11 分钟前
chromem-go + ollama + bge-m3 进行文档向量嵌入和查询
开发语言·数据库·golang
海外住宅ip供应商-luck30 分钟前
PHP如何搭建设置代理http并加密使用?
开发语言·http·php
南玖yy44 分钟前
Python 的未来:在多元变革中持续领跑
开发语言·python
南隅。1 小时前
【C++】基础3——正则表达式,静态多态(函数重载和模板),异常处理
开发语言·c++·正则表达式
乌拉_乌拉_乌拉1 小时前
C# string字符串介绍
开发语言·c#
JoLonn1 小时前
PHP中yield关键字的使用
大数据·开发语言·php
C#winform流程图1 小时前
c#winform,倒鸭子字幕效果,typemonkey字幕效果,抖音瀑布流字幕效果
开发语言·c#
Python×CATIA工业智造1 小时前
基于pycatia的CATIA零部件激活状态管理技术解析
python·pycharm·catia二次开发