爬虫

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')
相关推荐
m0_3743818121 小时前
分享一些成功的 SQL 优化案例
大数据·数据库·数据仓库·爬虫·python·oracle
小白学大数据1 天前
Pandas与Matplotlib:Python中的动态数据可视化
开发语言·爬虫·python·pandas·matplotlib
流浪的大萝卜2 天前
开发一个电商API接口的步骤!!!
java·大数据·前端·数据仓库·后端·爬虫·python
Bearjumpingcandy2 天前
爬虫全网抓取
爬虫
毕设木哥2 天前
25届计算机专业选题推荐-基于python的线上拍卖会管理系统【python-爬虫-大数据定制】
大数据·开发语言·数据库·爬虫·python·信息可视化·课程设计
全能全知者2 天前
python简单易懂的lxml读取HTML节点及常用操作方法
开发语言·爬虫·python·html
菜鸡中的奋斗鸡→挣扎鸡2 天前
初识爬虫3
爬虫
2401_872514972 天前
爬虫代理失效怎么处理?全面解决方案
网络·爬虫
布语world2 天前
航空航司reese84逆向
爬虫·python·安全