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

通过输入搜索的关键字,和搜索页数范围,爬出指定文本内内容并存入到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("文件保存成功!")
相关推荐
wuyk55512 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
wuyk5552 天前
Spider-第14讲-表单提交与CSRF
前端·爬虫·python·elasticsearch·csrf
wuyk5554 天前
Spider-第11讲-工程化改造与可维护性
大数据·爬虫·elasticsearch·搜索引擎
wuyk5554 天前
Spider-第12讲-asyncio异步并发爬取
大数据·爬虫·elasticsearch·搜索引擎
小宋10214 天前
AI 爬虫把大学图书馆站点拖垮:按行为指纹给爬虫分类、按类发配额、用边缘缓存分层,以带宽成本结构和真实用户 P95 延迟定档
人工智能·爬虫·分类
wuyk5555 天前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
wuyk5555 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
wuyk5556 天前
Spider-第07讲-JSON接口与正则提取
爬虫·python·json
feasibility.6 天前
一物降一物?AI逆向没有终局:REA拆App,BLA设套,LASIK清场
人工智能·爬虫·github·逆向·skill·rea
wuyk5558 天前
Spider-第03讲-HTTP速通与读懂响应
网络·爬虫·网络协议·http