python爬取百度
时间: 2023-08-21 17:03:24 浏览: 117
要使用Python爬取百度搜索结果,你可以使用requests库和BeautifulSoup库来发送HTTP请求并解析HTML页面。首先,你需要导入这两个库:
import requests
from bs4 import BeautifulSoup
接下来,你可以定义一个函数,例如get_baidu_search_result,来传入关键字作为参数。在函数中,你可以设置要爬取的URL和请求头信息:
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'}
然后,你可以使用requests库发送GET请求,并将响应内容传给BeautifulSoup库进行解析:
response = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
接着,你可以使用BeautifulSoup库的find_all方法查找搜索结果的div元素,并提取标题、链接和描述信息:
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
最后,你可以在主函数中调用get_baidu_search_result,并传入你想要搜索的关键字:
if __name__ == '__main__':
keyword = 'Python'
get_baidu_search_result(keyword)
这样,你就可以使用Python爬取百度搜索结果,并将标题、链接和描述信息打印出来了。记得要根据自己的需求进行进一步的处理和存储。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python爬虫:百度数据轻松抓取!](https://blog.csdn.net/oGuJing123/article/details/131225474)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [使用Python的爬虫框架Scrapy来爬取网页数据.txt](https://download.csdn.net/download/weixin_44609920/88225579)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [爬虫实战(三)](https://blog.csdn.net/m0_64357419/article/details/129629428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文