requests与bs4编码

本文介绍了在Python中使用requests库时如何处理响应内容的编码问题。包括response对象的.text属性如何工作,.content属性的使用场景,以及如何利用BeautifulSoup进行编码自动检测。

在使用requests库时,response对象的.text属性

r.text
默认的response对象的encoding属性是None,所以在调用r.text解码的时候,request会猜它的编码

If Response.encoding is None, encoding will be guessed using chardet.

encoding = None
Encoding to decode with when accessing r.text.

r.content
如果暂时不清楚编码是什么,则可以调用.content属性,它返回的是自己(bytes),就是还没有编码。然后让bs4库来解析。

bs4 编码
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id51

Beautiful Soup用了 编码自动检测 子库来识别当前文档编码并转换成Unicode编码. BeautifulSoup 对象的 .original_encoding 属性记录了自动识别编码的结果:

soup.original_encoding

参考文献:
http://docs.python-requests.org/zh_CN/latest/api.html#requests.Response.content

### 使用 `requests` 和 `BeautifulSoup` 进行网页数据爬取的教程 在 Python 中,`requests` `BeautifulSoup` 是两个广泛用于网络爬虫的核心库。`requests` 负责发送 HTTP 请求并获取网页响应内容,而 `BeautifulSoup` 则用于解析 HTML 文档并提取所需的数据[^3]。 #### 安装依赖库 在开始之前,需要确保安装了 `requests` 和 `beautifulsoup4` 库,可以通过以下命令进行安装: ```bash pip install requests beautifulsoup4 ``` #### 发送 HTTP 请求并获取页面内容 使用 `requests.get()` 方法可以向目标 URL 发送 GET 请求,并通过 `.text` 属性获取返回的 HTML 内容。建议在请求中添加异常处理以应对网络问题或无效响应的情况[^4]。 示例代码如下: ```python import requests def fetch_html(url): try: response = requests.get(url, timeout=10) response.raise_for_status() # 如果响应状态码不是 200,将抛出异常 response.encoding = response.apparent_encoding # 自动识别编码格式 return response.text except requests.RequestException as e: print(f"请求失败: {e}") return None ``` #### 解析 HTML 并提取数据 获取到 HTML 内容后,可以使用 `BeautifulSoup` 对其进行解析。通过查找特定的标签和类名,可以提取结构化的数据。 例如,假设要从一个网站抓取书籍信息(书名、作者、价格、销量),可以使用如下代码: ```python from bs4 import BeautifulSoup def parse_books(html_content): soup = BeautifulSoup(html_content, 'html.parser') books = [] for item in soup.select('.book-list li'): book = { 'title': item.select_one('.p-name a')['title'] if item.select_one('.p-name a') else None, 'author': item.select_one('.p-author a').get_text(strip=True) if item.select_one('.p-author a') else None, 'price': item.select_one('.p-price strong').get_text(strip=True) if item.select_one('.p-price strong') else None, 'sales': item.select_one('.p-commit a').get_text(strip=True) if item.select_one('.p-commit a') else None } books.append(book) return books ``` #### 完整示例:爬取图书销量榜数据 将上述功能整合为一个完整的脚本,可以实现对京东“计算机互联网类”图书销量榜日榜数据的爬取: ```python import requests from bs4 import BeautifulSoup def fetch_html(url): try: response = requests.get(url, timeout=10) response.raise_for_status() response.encoding = response.apparent_encoding return response.text except requests.RequestException as e: print(f"请求失败: {e}") return None def parse_books(html_content): soup = BeautifulSoup(html_content, 'html.parser') books = [] for item in soup.select('.book-list li'): book = { 'title': item.select_one('.p-name a')['title'] if item.select_one('.p-name a') else None, 'author': item.select_one('.p-author a').get_text(strip=True) if item.select_one('.p-author a') else None, 'price': item.select_one('.p-price strong').get_text(strip=True) if item.select_one('.p-price strong') else None, 'sales': item.select_one('.p-commit a').get_text(strip=True) if item.select_one('.p-commit a') else None } books.append(book) return books if __name__ == '__main__': url = 'https://book.jd.com/booktop/0-0-0.html?category=3287-0-0-0-1002-1#comfort' html = fetch_html(url) if html: books = parse_books(html) for book in books: print(book) ``` 该脚本首先通过 `fetch_html` 获取指定 URL 的 HTML 内容,然后调用 `parse_books` 提取书籍信息并输出。 #### 注意事项 - **反爬虫机制**:部分网站会对频繁访问的 IP 地址进行限制,因此建议在请求之间加入随机延迟(如 `time.sleep(random.uniform(1, 3))`)。 - **User-Agent 设置**:为了模拟浏览器行为,可以在请求头中设置合理的 `User-Agent` 字段。 - **合法性道德规范**:在进行网页数据抓取时,应遵守目标网站的 robots.txt 文件规定,并尊重其服务条款。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值