爬虫

robots.txt

https://www.baidu.com/robots.txt
robots.txt 文件是一个放置在网站根目录的文本文件,用于告诉搜索引擎的爬虫哪些页面或目录可以或不可以被爬取。

sh 复制代码
# 表示以下规则适用于哪些爬虫。
User-agent: *
# 禁止爬取该目录下的页面。
Disallow: /tmp/
# 允许爬取该目录下的页面。
Allow: /

requests

requests 官方文档:https://requests.readthedocs.io/projects/cn/zh-cn/latest/

python 复制代码
import requests
r = requests.get("http://www.baidu.com/s", params={"wd": "python"})
r = requests.post("http://www.baidu.com/s", data={"wd": "python"})
r = requests.get("http://www.baidu.com",headers={"User-Agent":"MyClient"})
print(r.content)# 二进制
print(r.text)# 源码
print(r.json()["data"])# json
print(r.url)
print(r.headers)
print(r.cookies)

会话对象

会话对象让你能够跨请求保持某些参数。

python 复制代码
import requests
s = requests.Session()
# 通过为会话对象的属性提供数据,实现为请求方法提供缺省数据
s.auth = ('user', 'pass')
# 方法层的参数(url 后面)会覆盖会话的参数,但是不会被跨请求保持。
r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})
r = s.get('http://httpbin.org/cookies')

前后文会话管理器

确保 with 区块退出后会话能被关闭,即使发生了异常也一样。

python 复制代码
with requests.Session() as s:
    s.get('http://httpbin.org/cookies')

SSL 证书验证

将 verify(默认为True) 设置为 False,Requests 也能忽略对 SSL 证书的验证。

python 复制代码
requests.get('https://kennethreitz.org', verify=False)

代理

python 复制代码
import requests
# http
proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
# Basic Auth
proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}
# SOCKS
proxies = {
    'http': 'socks5://user:pass@host:port',
    'https': 'socks5://user:pass@host:port'
}
requests.get("http://example.org", proxies=proxies)

Beautiful Soup

中文文档:https://beautifulsoup.cn/

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库。

python 复制代码
from bs4 import BeautifulSoup

r = requests.get('https://www.baidu.com')
soup = BeautifulSoup(r.text,'lxml')
# 通过 CSS 选择器或定位
content = soup.select('#id > div font')

XPath

XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。

教程:https://www.w3school.com.cn/xpath/index.asp

表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
... 选取当前节点的父节点。
@ 选取属性。
python 复制代码
from lxml import etree

html = requests.get('https://www.baidu.com')
soup = etree.HTML(html.text)
content = soup.xpath('//a/@href')
相关推荐
WeeJot嵌入式3 小时前
爬虫对抗:ZLibrary反爬机制实战分析
爬虫·python·网络安全·playwright·反爬机制
进击的雷神3 小时前
攻克JSON嵌套HTML的双重解析难题:基于多层数据提取的精准爬虫设计
爬虫·html·json·spiderflow
前端小趴菜~时倾4 小时前
自我提升-python爬虫学习:day05-函数与面向对象编程
爬虫·python·学习
进击的雷神4 小时前
攻克JSON接口分页与对象数组处理:基于AJAX数据源的精准博客爬虫设计
爬虫·ajax·json·spiderflow
vx_biyesheji00017 小时前
计算机毕业设计:Python汽车数据分析系统 Django框架 requests爬虫 可视化 车辆 数据分析 大数据 机器学习(建议收藏)✅
爬虫·python·算法·机器学习·django·汽车·课程设计
小白学大数据8 小时前
效率翻倍:Scrapy-Redis 分布式全站爬虫并发优化进阶
redis·分布式·爬虫·scrapy
tang7778919 小时前
小红书平台用什么代理 IP 比较好?2026年3月实测数据 + 选型推荐
网络·爬虫·python·网络协议·tcp/ip·数据挖掘·ip
进击的雷神1 天前
突破POST分页与IP封锁:基于表单提交和代理转发的新闻爬虫设计
爬虫·网络协议·tcp/ip
小邓睡不饱耶1 天前
东方财富股吧话题爬虫实现:从接口请求到Excel数据落地
爬虫·excel
进击的雷神1 天前
攻克动态列表页结构:基于ID与URL双字段协同提取的精准爬虫设计
爬虫·spiderflow