python爬取搜索结果并输出
时间: 2023-07-21 15:51:42 浏览: 165
好的,我可以帮你解决这个问题。你可以使用 Python 的 requests 库和 Beautiful Soup 库来实现爬取搜索结果并输出的功能。
以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置搜索关键词
keyword = 'Python 爬虫'
# 构造请求 URL
url = 'https://www.baidu.com/s?wd=' + keyword
# 发送请求
response = requests.get(url)
# 解析 HTML 页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取搜索结果列表
result_list = soup.find_all('div', {'class': 'result'})
# 输出搜索结果标题和链接
for result in result_list:
title = result.h3.text.strip()
link = result.a['href']
print(title, link)
```
这段代码会爬取百度搜索结果中包含关键词 "Python 爬虫" 的页面,并输出每个搜索结果的标题和链接。你可以根据自己的需要修改关键词、搜索引擎、输出格式等内容。
相关问题
python爬取关键字搜索内容输出标题跟链接
这是一个简单的Python爬虫程序,用于从搜索引擎中爬取与关键字相关的搜索结果,并输出标题和链接。
```python
import requests
from bs4 import BeautifulSoup
def 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")
results = soup.find_all("h3", {"class": "t"})
for result in results:
link = result.a.get("href")
title = result.a.text
print(title, link)
search("Python 爬虫")
```
在上面的代码中,我们使用`requests`和`BeautifulSoup`库来获取和解析搜索结果页面。我们首先定义了一个`search`函数,它接受一个关键字作为参数,并使用`requests.get`方法获取搜索结果页面。然后,我们使用`BeautifulSoup`将页面解析为一个`soup`对象。接下来,我们使用`soup.find_all`方法查找所有标题标签`<h3 class="t">`,并遍历它们以获取标题和链接。最后,我们使用`print`函数输出标题和链接。
我们调用`search`函数,并传递一个关键字作为参数。运行程序后,我们将看到与关键字相关的搜索结果页面的标题和链接。
python爬取搜索内容输出名称跟链接
以下是一个简单的Python爬虫程序,用于从百度搜索结果页面上提取结果名称和链接:
```python
import requests
from bs4 import BeautifulSoup
search_term = input("请输入要搜索的内容:")
url = "https://www.baidu.com/s"
params = {"wd": search_term}
response = requests.get(url, params=params)
soup = BeautifulSoup(response.text, "html.parser")
results = soup.find_all("div", class_="result")
for result in results:
title_element = result.find("h3", class_="t")
if title_element:
link_element = title_element.find("a")
if link_element:
title = link_element.text.strip()
link = link_element["href"].strip()
print(title)
print(link)
```
以上程序首先要求用户输入要搜索的内容,然后使用requests库向百度发送GET请求并传递搜索参数。接着,使用BeautifulSoup库对页面进行解析,并使用CSS选择器找到所有搜索结果的`<div>`元素。对于每个结果,程序查找标题元素的`<h3>`标签,然后在其中找到链接元素。如果找到了标题和链接元素,程序就输出它们的文本和链接。
阅读全文
相关推荐
















