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

通过输入搜索的关键字,和搜索页数范围,爬出指定文本内内容并存入到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("文件保存成功!")
相关推荐
大神薯条老师9 小时前
Python从入门到高手4.3节-掌握跳转控制语句
后端·爬虫·python·深度学习·机器学习·数据分析
wdxylb16 小时前
Pyhton爬虫使用Selenium实现浏览器自动化操作抓取网页
爬虫·selenium·测试工具
菜鸡中的奋斗鸡→挣扎鸡1 天前
初始爬虫11
开发语言·爬虫·python
凡人的AI工具箱1 天前
15分钟学 Python 第35天 :Python 爬虫入门(一)
开发语言·数据结构·人工智能·后端·爬虫·python
新缸中之脑1 天前
ScrapeGraphAI 大模型增强的网络爬虫
爬虫
易辰君1 天前
python爬虫 - 初识爬虫
开发语言·爬虫·python
人生の三重奏2 天前
爬虫——同步与异步加载
爬虫·jsonpath·同步与异步·腾讯新闻
人生の三重奏2 天前
爬虫——爬取小音乐网站
爬虫
能摆一天是一天2 天前
Python 爬虫 根据ID获得UP视频信息
开发语言·爬虫·python·selenium
NPE~3 天前
爬虫入门 & Selenium使用
爬虫·python·selenium·测试工具·xpath