安装必要的库
使用`pip`安装`requests`和`BeautifulSoup`库。
```bash
pip install requests beautifulsoup4
发送HTTP请求
使用`requests`库发送HTTP GET请求到目标网站,并指定查询参数。
```python
import requests
url = "https://example.com/search"
params = {"q": "查询词"}
response = requests.get(url, params=params)
解析HTML网页
使用`BeautifulSoup`库解析响应的HTML内容。
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
查找资料
利用CSS选择器等技术查找所需的资料,并提取其内容。
```python
获取网页标题
title = soup.title.string
print("网页标题:", title)
获取所有的链接
links = soup.find_all("a")
for link in links:
print("链接:", link.get("href"))
获取指定元素的内容
element = soup.find("div", class_="content")
print("内容:", element.text.strip())
遵循网站规则
注意查看并遵循目标网站的`robots.txt`文件,以及在使用代理时保护隐私。
重复搜索
重复上述步骤以搜索其他结果页面。
请确保在爬取网页数据时遵守相关法律法规和网站的使用条款,以及尊重网站所有者的意愿。