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

相关推荐
唐叔在学习2 分钟前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
2501_945423543 分钟前
使用Fabric自动化你的部署流程
jvm·数据库·python
wenlonglanying4 分钟前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
2401_846341655 分钟前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
未知鱼15 分钟前
Python安全开发之子域名扫描器(含详细注释)
网络·python·安全·web安全·网络安全
2401_8318249618 分钟前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
CQU_JIAKE20 分钟前
3.21【A】
开发语言·php
2401_8579182928 分钟前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
今儿敲了吗31 分钟前
python基础学习笔记第九章——模块、包
开发语言·python
xyq202437 分钟前
TypeScript 命名空间
开发语言