从维基百科通过关键字爬取指定文本内容

通过输入搜索的关键字,和搜索页数范围,爬出指定文本内内容并存入到txt文档。代码逐行讲解。

使用re、res、BeautifulSoup包读取,代码已测,可以运行。txt文档内容不乱码。

python 复制代码
import re
import requests
from bs4 import BeautifulSoup

titles = []                                                             #存放文档标题
urls = []                                                               #存放每个文档链接

keyword = input("请输入想要查找的关键字:")                              
pagenum = input("请输入想要查找的页数:")                                        
txt_name = keyword + ":前" + pagenum + "页内容.txt"                        

with open(txt_name,'w',encoding='utf-8') as f:                             # 创建txt文件
    f.write(txt_name + '\r')                                               # 将文件名写入
    f.close()

# 每页内容单独爬取
for i in range(1, int(pagenum)+1):                               
    html = "http://www.ofweek.com/newquery.action?keywords="+keyword+"&type=1&pagenum=" + str(i)         # 根据关键词和页数生成链接

    resp = requests.get(html)                             # get获取数据,访问拼接后的url                                    
    resp.encoding = 'gb18030'                             # 读取中文时不会出现乱码
    content = resp.text                  # 拿到网站的数据,捕获到的网页内容给content变量
    
    # html文件解析,解析响应的文件内容,html.text 是 HTML 文档的源代码,
    # 'html.parser' 是解析器,用于指定如何解析 HTML 文档
    bs = BeautifulSoup(content,'html.parser')
    #每个标题都存在类名为no-pic的li标签里面
    for news in bs.select('div.zx-tl'): 
        url = news.select('a')[0]['href']                     # 提取文章链接
        urls.append(url) 
        title = news.select('a')[0].text                      # 提取文章标题
        titles.append(title)

for i in range(len(urls)):                                    # 遍历每篇文章的链接
    resp = requests.get(urls[i])
    resp.encoding='gb18030'
    content = resp.text
    bs = BeautifulSoup(content,'html.parser')
    #文章的内容是存在类名为artical-content的div块里面
    page_content = bs.select('div.artical-content')[0].text
    with open(txt_name,'a',encoding='utf-8') as f:            # 写入txt文件
        f.write("\n"+titles[i]+page_content)
        f.close()

print("文件保存成功!")
相关推荐
interception6 小时前
爬虫逆向,瑞数6,补环境,国家专利
javascript·爬虫·python·网络爬虫
麦麦大数据7 小时前
F053 投标推荐可视化系统+推荐算法vue+flask+爬虫
vue.js·爬虫·flask·可视化·推荐算法·招投标
weixin_4686352911 小时前
用python获取双色球历史数据,纯数据处理,非爬虫
开发语言·爬虫·python
qq_2526144113 小时前
python爬虫爬取视频
开发语言·爬虫·python
猫头虎1 天前
PyCharm 2025.3 最新变化:值得更新吗?
ide·爬虫·python·pycharm·beautifulsoup·ai编程·pip
有味道的男人2 天前
1688数据采集:官方API与网页爬虫实战指南
java·服务器·爬虫
有味道的男人2 天前
Python 爬虫框架设计:类封装与工程化实践
开发语言·爬虫·python
老王Bingo2 天前
Qwen Code + Chrome DevTools MCP,让爬虫、数据采集、自动化测试效率提升 100 倍
前端·爬虫·chrome devtools
小白学大数据2 天前
拼多多数据抓取:Python 爬虫中的 JS 逆向基础案例分析
开发语言·javascript·爬虫·python
道法自然|~2 天前
【PHP】简单的脚本/扫描器拦截与重要文件保护
开发语言·爬虫·php