爬虫

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')
相关推荐
孤狼warrior30 分钟前
公司信息建设库数据 使用调用堆栈的JS逆向爬虫
javascript·爬虫
艾莉丝努力练剑5 小时前
【自动化测试实战篇】Web自动化测试实战:从用例编写到报告生成
前端·人工智能·爬虫·python·pycharm·自动化·测试
1***s63215 小时前
Python爬虫反爬策略,User-Agent与代理IP
开发语言·爬虫·python
Glommer1 天前
AST 反混淆处理示例
javascript·爬虫
q***31832 天前
爬虫基础之爬取某基金网站+数据分析
爬虫·数据挖掘·数据分析
嫂子的姐夫2 天前
23-MD5+DES+Webpack:考试宝
java·爬虫·python·webpack·node.js·逆向
HoneyMoose2 天前
AI Bot 爬虫新势力
人工智能·爬虫
Miku162 天前
LangGraph+BrightData+PaperSearch的研究助理
爬虫·langchain·mcp
自学互联网2 天前
python爬虫入门案例day05:Pexels
开发语言·爬虫·python