用BeautifulSoup实现对http://news.imnu.edu.cn/的爬取
时间: 2023-12-27 09:05:32 浏览: 38
可以使用以下代码实现对http://news.imnu.edu.cn/的爬取:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://news.imnu.edu.cn/'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 爬取新闻标题
titles = soup.find_all('div', class_='list_item')
for title in titles:
print(title.find('a').text.strip())
# 爬取新闻链接
links = soup.find_all('div', class_='list_item')
for link in links:
print(url + link.find('a')['href'])
```
这段代码利用了Python中的requests和BeautifulSoup库来获取网页内容并解析网页。首先使用requests.get方法获取网页内容,然后使用BeautifulSoup进行解析和筛选需要的内容。在这个例子中,我们爬取了新闻标题和链接。需要注意的是,在使用BeautifulSoup时,要根据网页的具体结构来选择合适的解析方法。
相关问题
用xpath和beautifulsoup爬取http://shehui.sanyau.edu.cn/?article/type/60/1.html新闻标题和浏览量
好的,您可以使用以下代码来获取http://shehui.sanyau.edu.cn/?article/type/60/1.html的所有新闻标题和浏览量:
```python
import requests
from bs4 import BeautifulSoup
# 发送HTTP请求
url = "http://shehui.sanyau.edu.cn/?article/type/60/1.html"
response = requests.get(url)
# 使用BeautifulSoup解析HTML文档
soup = BeautifulSoup(response.text, features='lxml')
# 获取所有新闻标题和浏览量
news_titles = soup.find_all('a', class_='main-title')
news_views = soup.find_all('span', class_='look')
# 打印结果
for i in range(len(news_titles)):
print(news_titles[i].string.strip(), news_views[i].string.strip())
```
注意需要提前安装requests和beautifulsoup4库。
用xpath和beautifulsoup爬取http://shehui.sanyau.edu.cn/?article/type/60/1.htm前5页l新闻标题和浏览量
好的,我可以帮您解决这个问题。以下是Python代码:
``` python
import requests
from bs4 import BeautifulSoup
for page in range(1, 6):
url = f"http://shehui.sanyau.edu.cn/?article/type/60/{page}.htm"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
articles = soup.find_all("div", class_="article")
for article in articles:
title = article.find("a").get_text()
views = article.find("i").get_text()
print(f"标题:{title} 浏览量:{views}")
```
这段代码将爬取 http://shehui.sanyau.edu.cn/?article/type/60/1.htm 前5页的新闻标题和浏览量,并打印输出。其中使用了 requests 库发送 HTTP 请求,使用了 BeautifulSoup 库进行 HTML 解析,同时使用了 xpath 和 find 方法来筛选出需要的数据。