python百度搜索的代码
时间: 2023-10-02 14:12:58 浏览: 42
以下是使用 Python 在百度进行搜索的示例代码:
```python
import requests
from bs4 import BeautifulSoup
search_query = "Python" # 搜索查询关键字
page_num = 0 # 搜索结果页数,0 表示第一页
url = f"https://www.baidu.com/s?wd={search_query}&pn={page_num}"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
# 提取搜索结果标题和链接
for result in soup.select(".t a"):
title = result.text
link = result.get("href")
print(f"{title}: {link}\n")
```
这段代码通过 `requests` 库发送 HTTP 请求获取搜索结果页面,然后使用 `BeautifulSoup` 库解析 HTML 页面并提取搜索结果的标题和链接。你可以根据需要修改搜索查询关键词和页数来获取不同的搜索结果。
相关问题
python百度爬虫代码
以下是一个简单的Python百度爬虫代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 搜索关键字
keyword = 'Python'
# 搜索起始页码
start_page = 0
# 搜索结果数
result_num = 10
# 构造搜索链接
search_url = f'https://www.baidu.com/s?wd={keyword}&pn={start_page}&rn={result_num}'
# 发送HTTP请求
response = requests.get(search_url)
# 解析HTML页面
soup = BeautifulSoup(response.content, 'html.parser')
# 查找所有搜索结果的标题和链接
results = soup.find_all('h3', class_='t')
for result in results:
# 获取标题和链接
title = result.a.get_text()
link = result.a['href']
# 打印搜索结果
print(title)
print(link)
```
该代码使用requests库发送HTTP请求,使用BeautifulSoup库解析HTML页面,然后查找所有搜索结果的标题和链接,并打印输出。你可以根据自己的需求修改关键字、起始页码和搜索结果数等参数来进行搜索。
爬虫python百度代码
以下是爬取百度搜索内容的Python代码示例:
```python
import requests
from bs4 import BeautifulSoup
def baidu_search(keyword):
url = 'https://www.baidu.com/s'
params = {'wd': keyword}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
search_results = soup.find_all('h3', {'class': 't'})
for result in search_results:
print(result.get_text())
baidu_search('Python爬虫')
```
这段代码实现了使用Python爬虫爬取百度搜索内容的功能。首先,通过requests库发送HTTP请求,然后使用BeautifulSoup库解析网页内容,最后找到搜索结果并打印出来。