python代码实现爬求搜狐新闻
时间: 2023-11-15 22:04:00 浏览: 50
要实现爬取搜狐新闻的Python代码,需要使用requests和BeautifulSoup库。以下是一个简单的示例代码:
```
import requests
from bs4 import BeautifulSoup
import re
url = 'http://www.sohu.com/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取新闻标题
news_titles = []
for news in soup.find_all("div", attrs={'class': 'news-wrapper'}):
title = news.find('a').text.strip()
news_titles.append(title)
# 获取移动端新闻标题
mobile_news_titles = re.findall('"mobileTitle":"(.*?)",', str(soup))
print("PC端新闻标题:")
for title in news_titles:
print(title)
print("移动端新闻标题:")
for title in mobile_news_titles:
print(title)
```
这段代码首先使用requests库获取搜狐首页的HTML代码,然后使用BeautifulSoup库解析HTML代码。接着,使用find_all方法找到所有class为"news-wrapper"的div标签,再从中提取出新闻标题。另外,使用正则表达式从HTML代码中提取出移动端新闻标题。最后,将获取到的新闻标题打印输出。