使用requests或urllib库,以及bs4库爬取https://www.gdqy.edu.cn/gqxw1.htm网页内容。 爬取包括: 1、广轻新闻,即从以下入口进去的所有新闻 爬取的新闻内容以及保存方式: 1、爬取的内容 所有新闻只抽取有效的“标题”,“正文”文本内容,以及本新闻的url地址,其他内容忽略。 2、保存形式 将所有爬取的内容保存到gdqy目录中。 每条新闻保存到一个文件中,文件名以递增数字为文件名,后缀为.txt。比如第一条新闻保存到1.txt,第二条保存到2.txt。 在保存的文件中,第一行为url地址,第二行为标题(如无标题则是空行),第三行及之后是此新闻的正文内容。
时间: 2024-04-04 19:30:52 浏览: 15
好的,这是一个爬取网页内容的问题。首先需要安装requests和bs4库,然后可以按照以下步骤进行:
```python
import requests
from bs4 import BeautifulSoup
# 请求网页内容
url = 'https://www.gdqy.edu.cn/gqxw1.htm'
response = requests.get(url)
html = response.content.decode('utf-8')
# 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
news_list = soup.find_all('div', class_='list_zw')
# 遍历每条新闻,保存到本地文件
for i, news in enumerate(news_list):
title = news.find('a').text.strip()
link = news.find('a').get('href')
if not link.startswith('http'):
link = 'https://www.gdqy.edu.cn' + link
content_response = requests.get(link)
content_html = content_response.content.decode('utf-8')
content_soup = BeautifulSoup(content_html, 'html.parser')
content = content_soup.find('div', class_='TRS_Editor').text.strip()
filename = f'gdqy/{i+1}.txt'
with open(filename, 'w', encoding='utf-8') as f:
f.write(link + '\n')
f.write(title + '\n\n')
f.write(content)
```
解释一下上面的代码:
1. 首先使用requests库请求网页内容,并且将响应的内容转换为UTF-8编码的字符串。
2. 然后使用BeautifulSoup库解析HTML文档,找到所有新闻条目的div元素。
3. 遍历每条新闻,找到新闻标题和链接,然后请求链接的内容,再次使用BeautifulSoup库解析HTML文档,找到新闻的正文。
4. 最后将新闻保存到以递增数字为文件名的txt文件中,每个文件包含新闻链接、新闻标题和新闻正文。