怎么才能实现把网页里的10篇文章用txt文档保存到工作目录里
示例代码如下
import requests
from bs4 import BeautifulSoup
html=requests.get('https://www.pythontab.com/html/pythonjichu/').text
soup=BeautifulSoup(html,'html.parser')
items=[]
alist=soup.select('#catlist a')
for a in alist:
href=a['href']
html=requests.get(href).text#获取文章详情
soup=BeautifulSoup(html,'html.parser')
item={}
title=soup.select('h1')[0].text#标题
content=soup.select('#Article .content')[0].text#内容
item['url']=href
item['title']=title
item['content']=content
items.append(item)
with open('articles.txt','w',encoding='utf-8') as f:
for item in items:
f.write('网址:'+item['url']+'\n')
f.write('标题:'+item['title']+'\n')
f.write('内容\n'+item['content']+'\n\n\n')
用requests请求库请求这10篇文章,解析其中的文本数据,可使用bs4或者re正则进行解析,之后写入到txt文件中。
你可以用requests库获取网页内容,然后使用BeautifulSoup库来解析网页,最后使用Python内置的文件操作函数将解析出来的文章内容保存为txt文件
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!#读取停顿词列表
stopword_list = [k.strip() for k in open('stopwords.txt', encoding='utf8').readlines() if k.strip() != '']
这一行代码有点长,用到的python知识点有:列表生成式、readlines和strip(),下文依次介绍。
首先需要使用Python爬虫将网页中的10篇文章爬取下来,可以使用requests库和BeautifulSoup库实现。具体步骤如下:
1.引入requests库和BeautifulSoup库。
import requests
from bs4 import BeautifulSoup
2.使用requests库下载网页,并解析网页内容。
url = 'http://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
3.通过BeautifulSoup库解析网页,获取需要爬取的文章内容。
articles = soup.select('.article')
接下来,需要将爬取下来的10篇文章保存为txt文档,并将它们存储到工作目录下。可以使用Python的文件读写功能实现。具体步骤如下:
1.在工作目录下创建一个名为articles的文件夹,用于存储文章。
import os
if not os.path.exists('articles'):
os.mkdir('articles')
2.循环遍历获取的文章,将每篇文章保存为一个txt文件,并将文件保存在articles文件夹下。
for i, article in enumerate(articles):
# 获取文章标题和内容,并创建txt文件
title = article.select_one('.title').text.strip()
content = article.select_one('.content').text.strip()
with open(f'articles/{i+1}_{title}.txt', 'w', encoding='utf-8') as f:
f.write(content)
这样就可以将网页中的10篇文章保存为txt文档,并将它们存储到工作目录下的articles文件夹中了。