用Python写一个百度关键词查询代码检索搜索结果中前五页的搜索链接检索链接和搜索关键词可自定义设置
以下是一个示例代码,你可以根据自己的需要进行修改:
import requests
from bs4 import BeautifulSoup
# 设置关键词和页数
keyword = "Python"
pages = 5
# 循环检索前五页的搜索结果链接
for i in range(pages):
url = f"https://www.baidu.com/s?wd={keyword}&pn={i*10}"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
results = soup.find_all("div", class_="result")
# 输出每个搜索结果的标题和链接
for r in results:
try:
link = r.find("a")["href"]
title = r.find("a").get_text()
print(title)
print(link)
except:
continue
在这个示例代码中,我们使用了 requests 库和 BeautifulSoup 库来发送 HTTP 请求和解析 HTML 文档。我们通过循环检索前五页的搜索结果链接,并使用 find_all() 方法来找到每个搜索结果的 div 元素。然后使用 find() 方法来找到链接和标题的 a 元素,并使用 get_text() 方法来获取标题的文本内容。最后,我们输出标题和链接。
注意,由于百度的搜索结果页面结构可能会发生变化,因此你可能需要根据实际情况进行修改。
原文地址: https://www.cveoy.top/t/topic/bxJV 著作权归作者所有。请勿转载和采集!