编写一个程序,分别使用urllib和requests爬取关于Python的百度搜索界面
时间: 2024-09-14 17:06:03 浏览: 83
编写一个同时使用`urllib`和`requests`库从百度搜索“Python”获取页面内容的简单Python程序,首先需要了解这两个库的基本用途。`urllib`是Python标准库的一部分,主要用于处理URL,而`requests`是一个更易使用的HTTP库。
以下是两个示例:
**使用`urllib`的例子**:
```python
import urllib.request
from bs4 import BeautifulSoup
def fetch_baidu_search_with_urllib():
url = "https://www.baidu.com/s?wd=Python"
try:
response = urllib.request.urlopen(url)
content = response.read().decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
# 这里你可以提取HTML中的信息,比如搜索结果标题等
print(soup.find_all('h3')) # 查找所有h3元素作为例子
except Exception as e:
print(f"Error occurred: {e}")
fetch_baidu_search_with_urllib()
```
**使用`requests`的例子**:
```python
import requests
from bs4 import BeautifulSoup
def fetch_baidu_search_with_requests():
url = "https://www.baidu.com/s?wd=Python"
try:
response = requests.get(url)
content = response.text
soup = BeautifulSoup(content, 'html.parser')
# 同样可以提取搜索结果的信息
print(soup.find_all('h3'))
阅读全文
相关推荐


















