python爬虫百度搜索
时间: 2023-08-14 16:02:32 浏览: 104
BaiduImage_爬虫_python_百度图片_
Python爬虫百度搜索可以使用Python的requests库和BeautifulSoup库来实现。首先,我们可以使用requests库发送HTTP请求,获取百度搜索结果页面的HTML代码。然后,使用BeautifulSoup库对HTML代码进行解析,提取出搜索结果的标题、链接和描述信息。以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_baidu_search_result(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')
results = soup.find_all('div', class_='result')
for result in results:
try:
title = result.h3.a.text
link = result.h3.a['href']
desc = result.find('div', class_='c-abstract').text
print(title)
print(link)
print(desc)
except:
pass
if __name__ == '__main__':
keyword = 'Python'
get_baidu_search_result(keyword)
```
这段代码会输出搜索结果的标题、链接和描述信息。你可以将关键字修改为你想要搜索的内容,然后运行代码即可获取百度搜索结果页面的相关信息。[1]
阅读全文