用xpath和beautifulsoup爬取http://shehui.sanyau.edu.cn/?article/type/60/1.html新闻标题和浏览量
时间: 2023-10-10 11:15:36 浏览: 41
好的,您可以使用以下代码来获取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 方法来筛选出需要的数据。
用xpath爬取http://shehui.sanyau.edu.cn/?article/type/60/1.html新闻标题和浏览量
好的,以下是使用xpath爬取http://shehui.sanyau.edu.cn/?article/type/60/1.html新闻标题和浏览量的代码示例:
```python
import requests
from lxml import etree
url = 'http://shehui.sanyau.edu.cn/?article/type/60/1.html'
response = requests.get(url)
html = response.text
selector = etree.HTML(html)
# 获取新闻标题
title_list = selector.xpath('//div[@class="li_title"]/a/text()')
for title in title_list:
print(title)
# 获取浏览量
views_list = selector.xpath('//div[@class="li_title"]/span/text()')
for views in views_list:
print(views)
```
需要注意的是,该网站对于爬虫的访问有一定的限制,请在爬取时适当设置访问间隔,避免给对方服务器带来过大负担。另外,使用 xpath 爬取数据时,需要根据实际网页源代码中的元素结构和属性信息进行调整,本示例代码仅供参考。