爬虫

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')
相关推荐
深蓝电商API2 小时前
常见反爬虫策略与破解方案汇总
爬虫
(时光煮雨)8 小时前
【Python进阶】Python爬虫-Selenium
爬虫·python·selenium
嫂子的姐夫8 小时前
10-七麦js扣代码
前端·javascript·爬虫·python·node.js·网络爬虫
深蓝电商API14 小时前
将爬虫部署到服务器:Scrapy+Scrapyd 实现定时任务与监控
服务器·爬虫·scrapy
nightunderblackcat15 小时前
四大名著智能可视化推演平台
前端·网络·爬虫·python·状态模式
数据牧羊人的成长笔记19 小时前
python爬虫scrapy框架使用
爬虫·python·scrapy
Fairy_sevenseven1 天前
[1]python爬虫入门,爬取豆瓣电影top250实践
开发语言·爬虫·python
white-persist1 天前
MCP协议深度解析:AI时代的通用连接器
网络·人工智能·windows·爬虫·python·自动化
深蓝电商API1 天前
不止是 Python:聊聊 Node.js/Puppeteer 在爬虫领域的应用
爬虫·python·node.js
摩羯座-185690305942 天前
爬坑 10 年!京东店铺全量商品接口实战开发:从分页优化、SKU 关联到数据完整性闭环
linux·网络·数据库·windows·爬虫·python