爬虫

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:[email protected]: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')
相关推荐
小白学大数据11 分钟前
基于Python的携程国际机票价格抓取与分析
开发语言·爬虫·python
火龙谷15 小时前
【爬虫】deepseek谈爬虫工具
爬虫
前端没钱16 小时前
在Electron中爬取CSDN首页的文章信息
前端·javascript·爬虫·electron
YONG823_API1 天前
借助电商 API 接口实现电商平台商品数据分析的详细步骤分享
数据库·爬虫·microsoft·数据挖掘·数据分析
jiaoxingk2 天前
多线程爬虫中实现线程安全的MySQL连接池
爬虫·mysql·安全
不会飞的鲨鱼2 天前
Scrapy框架之CrawlSpider爬虫 实战 详解
爬虫·scrapy
API小爬虫2 天前
利用 Python 爬虫按关键字搜索 1688 商品详情:实战指南
开发语言·爬虫·python
Luck_ff08102 天前
【Python爬虫详解】第五篇:使用正则表达式提取网页数据
爬虫·python·正则表达式
xixixiLucky2 天前
爬虫学习笔记(一)
笔记·爬虫·学习
一个天蝎座 白勺 程序猿2 天前
Python爬虫(10)Python数据存储实战:基于pymongo的MongoDB开发深度指南
数据库·爬虫·mongodb