用python爬取 http://www.news.cn/politics/leaders/2023- 04/28/c_1129576764.htm并采用 CSS 选择器筛选元素 的方法提取日期。
时间: 2023-10-06 20:12:13 浏览: 48
好的,以下是用Python爬取并筛选元素的代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.news.cn/politics/leaders/2023-04/28/c_1129576764.htm'
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
date = soup.select_one('.h-time').text.strip()
print(date)
```
解释一下代码:
首先导入了requests和BeautifulSoup库,然后指定要爬取的URL地址,并使用requests库的get方法获取该网页的HTML文本。
然后使用BeautifulSoup库将获取到的HTML文本解析成一个BeautifulSoup对象。
接下来使用CSS选择器选取日期所在的元素,这里我们选取一个class为'h-time'的元素。由于我们只需要日期的文本内容,所以再通过text属性获取元素的文本内容,并使用strip方法删除多余的空格。
最后,将提取到的日期打印输出。
相关问题
用python爬取新闻网页(URL:http://www.news.cn/politics/leaders/2023- 04/28/c_1129576764.htm)中的新闻文本。
可以使用 Python 中的 requests 和 BeautifulSoup 库来实现这个功能。
首先,使用 requests 库获取网页的 HTML 内容:
```python
import requests
url = 'http://www.news.cn/politics/leaders/2023-04/28/c_1129576764.htm'
response = requests.get(url)
html_content = response.content
```
然后,使用 BeautifulSoup 库解析 HTML 内容,提取新闻文本:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
news_content = soup.find('div', class_='article').text.strip()
```
最后,输出新闻文本:
```python
print(news_content)
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.news.cn/politics/leaders/2023-04/28/c_1129576764.htm'
response = requests.get(url)
html_content = response.content
soup = BeautifulSoup(html_content, 'html.parser')
news_content = soup.find('div', class_='article').text.strip()
print(news_content)
```
public static void main(string[] args) {// 1、创建多个各类新闻标题对象ne
wsTitle1 = new NewsTitle("Sports", "Lionel Messi wins FIFA Ballon d'Or");
NewsTitle newsTitle2 = new NewsTitle("Technology", "Apple unveils new iPhone 13 with 5G support");
NewsTitle newsTitle3 = new NewsTitle("Entertainment", "Taylor Swift releases new album 'Red (Taylor's Version)'");
NewsTitle newsTitle4 = new NewsTitle("Politics", "President Biden signs infrastructure bill into law");
// 2、将新闻标题对象添加到一个列表中
List<NewsTitle> newsTitlesList = new ArrayList<>();
newsTitlesList.add(newsTitle1);
newsTitlesList.add(newsTitle2);
newsTitlesList.add(newsTitle3);
newsTitlesList.add(newsTitle4);
// 3、遍历列表并打印新闻标题
for (NewsTitle newsTitle : newsTitlesList) {
System.out.println(newsTitle.getCategory() + ": " + newsTitle.getTitle());
}
}