爬取一下百度首页的今日热搜 用python
时间: 2024-01-01 15:05:22 浏览: 24
可以使用Python中的requests和BeautifulSoup库来实现这个需求。具体代码如下:
```
import requests
from bs4 import BeautifulSoup
url = 'http://www.baidu.com/s?wd=%E7%83%AD%E6%90%9C&tn=json&rn=50'
# 发送请求,获取网页内容
response = requests.get(url).text
# 解析网页内容
soup = BeautifulSoup(response, 'html.parser')
# 获取热搜词汇的列表
hot_search_list = soup.select('#content_left div#hotsearchid li a span')
# 输出热搜词汇
for index, hot_search in enumerate(hot_search_list):
print(f'[{index + 1}] {hot_search.get_text()}')
```
运行代码后,会输出百度首页的今日热搜列表。请注意,百度可能会对爬虫进行限制,建议不要频繁使用该代码。
相关问题
使用python爬取百度热搜
好的,您可以使用Python中的requests和beautifulsoup模块来爬取百度热搜榜单。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = "http://top.baidu.com/buzz?b=1"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
# 获取热搜榜单中的所有条目
items = soup.find_all("a", class_="list-title")
# 输出每个条目的标题和链接
for item in items:
print(item.text)
print(item["href"])
```
此代码将输出百度热搜榜单中的所有标题和链接。您可以根据需要对此进行修改和扩展。
python爬取百度热搜榜
以下是使用Python爬取百度热搜榜的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送HTTP请求获取网页内容
url = 'https://www.baidu.com/s?wd=%E7%83%AD%E6%90%9C%E6%A6%9C'
response = requests.get(url)
html_content = response.text
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(html_content, 'html.parser')
# 定位热搜榜的元素
hot_searches = soup.find_all('a', class_='title-content-title')
# 打印热搜榜的内容
for hot_search in hot_searches:
print(hot_search.text)
```
这段代码使用了requests模块发送HTTP请求,然后使用BeautifulSoup模块解析HTML内容。通过定位热搜榜的元素,我们可以获取到热搜榜的内容,并将其打印出来。