搜索
首页后端开发Python教程python3根据关键词爬取百度百科的内容

前言

关于python版本,我一开始看很多资料说python2比较好,因为很多库还不支持3,但是使用到现在为止觉得还是pythin3比较好用,因为编码什么的问题,觉得2还是没有3方便。而且在网上找到的2中的一些资料稍微改一下也还是可以用。

好了,开始说爬百度百科的事。

这里设定的需求是爬取北京地区n个景点的全部信息,n个景点的名称是在文件中给出的。没有用到api,只是单纯的爬网页信息。 

1、根据关键字获取url

由于只需要爬取信息,而且不涉及交互,可以使用简单的方法而不需要模拟浏览器。

可以直接

<strong>http://www.php.cn/"guanjianci"</strong>

<strong>for </strong>l <strong>in </strong>view_names:
 <strong>&#39;&#39;&#39;http://baike.baidu.com/search/word?word=&#39;&#39;&#39; </strong><em># 得到url的方法
</em><em> </em>name=urllib.parse.quote(l)
 name.encode(<strong>&#39;utf-8&#39;</strong>)
 url=<strong>&#39;http://baike.baidu.com/search/word?word=&#39;</strong>+name

这里要注意关键词是中午所以要注意编码问题,由于url中不能出现空格,所以需要用quote函数处理一下。

关于quote():

在 Python2.x 中的用法是:urllib.quote(text)  。Python3.x 中是urllib.parse.quote(text)   。按照标准,URL只允许一部分ASCII 字符(数字字母和部分符号),其他的字符(如汉字)是不符合URL标准的。所以URL中使用其他字符就需要进行URL编码。URL中传参数的部分(query String),格式是:name1=value1&name2=value2&name3=value3。假如你的name或者value值中的『&』或者『=』等符号,就当然会有问题。所以URL中的参数字符串也需要把『&=』等符号进行编码。URL编码的方式是把需要编码的字符转化为%xx的形式。通常URL编码是基于UTF-8的(当然这和浏览器平台有关)

例子:

比如『我,unicode 为 0x6211,UTF-8编码为0xE60x880x91,URL编码就是 %E6%88%91。

Python的urllib库中提供了quotequote_plus两种方法。这两种方法的编码范围不同。不过不用深究,这里用quote就够了。 

2、下载url

用urllib库轻松实现,见下面的代码中def download(self,url) 

3、利用Beautifulsoup获取html 

4、数据分析

百科中的内容是并列的段,所以在爬的时候不能自然的按段逻辑存储(因为全都是并列的)。所以必须用正则的方法。

基本的想法就是把整个html文件看做是str,然后用正则的方法截取想要的内容,在重新把这段内容转换成beautifulsoup对象,然后在进一步处理。

可能要花些时间看一下正则。

代码中还有很多细节,忘了再查吧只能,下次绝对应该边做编写文档,或者做完马上写。。。

贴代码!

# coding:utf-8
&#39;&#39;&#39;
 function:爬取百度百科所有北京景点,
 author:yi
&#39;&#39;&#39;
import urllib.request
from urllib.request import urlopen
from urllib.error import HTTPError
import urllib.parse
from bs4 import BeautifulSoup
import re
import codecs
import json
 
class BaikeCraw(object):
 def __init__(self):
  self.urls =set()
  self.view_datas= {}
 
 def craw(self,filename):
  urls = self.getUrls(filename)
  if urls == None:
   print("not found")
  else:
   for urll in urls:
    print(urll)
    try:
     html_count=self.download(urll)
     self.passer(urll, html_count)
    except:
     print("view do not exist")
    &#39;&#39;&#39;file=self.view_datas["view_name"]
    self.craw_pic(urll,file,html_count)
     print(file)&#39;&#39;&#39;
 
 
 def getUrls (self, filename):
  new_urls = set()
  file_object = codecs.open(filename, encoding=&#39;utf-16&#39;, )
  try:
   all_text = file_object.read()
  except:
   print("文件打开异常!")
   file_object.close()
  file_object.close()
  view_names=all_text.split(" ")
  for l in view_names:
   if &#39;?&#39; in l:
    view_names.remove(l)
  for l in view_names:
   &#39;&#39;&#39;http://baike.baidu.com/search/word?word=&#39;&#39;&#39; # 得到url的方法
   name=urllib.parse.quote(l)
   name.encode(&#39;utf-8&#39;)
   url=&#39;http://baike.baidu.com/search/word?word=&#39;+name
   new_urls.add(url)
  print(new_urls)
  return new_urls
 
 def manger(self):
  pass
 
 def passer(self,urll,html_count):
  soup = BeautifulSoup(html_count, &#39;html.parser&#39;, from_encoding=&#39;utf_8&#39;)
  self._get_new_data(urll, soup)
  return
 
 def download(self,url):
  if url is None:
   return None
  response = urllib.request.urlopen(url)
  if response.getcode() != 200:
   return None
  return response.read()
 
 def _get_new_data(self, url, soup): ##得到数据
  if soup.find(&#39;p&#39;,class_="main-content").find(&#39;h1&#39;) is not None:
   self.view_datas["view_name"]=soup.find(&#39;p&#39;,class_="main-content").find(&#39;h1&#39;).get_text()#景点名
   print(self.view_datas["view_name"])
  else:
   self.view_datas["view_name"] = soup.find("p", class_="feature_poster").find("h1").get_text()
  self.view_datas["view_message"] = soup.find(&#39;p&#39;, class_="lemma-summary").get_text()#简介
  self.view_datas["basic_message"]=soup.find(&#39;p&#39;, class_="basic-info cmn-clearfix").get_text() #基本信息
  self.view_datas["basic_message"]=self.view_datas["basic_message"].split("\n")
  get=[]
  for line in self.view_datas["basic_message"]:
   if line != "":
   get.append(line)
  self.view_datas["basic_message"]=get
  i=1
  get2=[]
  tmp="%%"
  for line in self.view_datas["basic_message"]:
 
   if i % 2 == 1:
    tmp=line
   else:
    a=tmp+":"+line
    get2.append(a)
   i=i+1
  self.view_datas["basic_message"] = get2
  self.view_datas["catalog"] = soup.find(&#39;p&#39;, class_="lemma-catalog").get_text().split("\n")#目录整体
  get = []
  for line in self.view_datas["catalog"]:
   if line != "":
    get.append(line)
  self.view_datas["catalog"] = get
  #########################百科内容
  view_name=self.view_datas["view_name"]
  html = urllib.request.urlopen(url)
  soup2 = BeautifulSoup(html.read(), &#39;html.parser&#39;).decode(&#39;utf-8&#39;)
  p = re.compile(r&#39;&#39;, re.DOTALL) # 尾
  r = p.search(content_data_node)
  content_data = content_data_node[0:r.span(0)[0]]
  lists = content_data.split(&#39;&#39;)
  i = 1
  for list in lists:#每一大块
   final_soup = BeautifulSoup(list, "html.parser")
   name_list = None
   try:
    part_name = final_soup.find(&#39;h2&#39;, class_="title-text").get_text().replace(view_name, &#39;&#39;).strip()
    part_data = final_soup.get_text().replace(view_name, &#39;&#39;).replace(part_name, &#39;&#39;).replace(&#39;编辑&#39;, &#39;&#39;) # 历史沿革
    name_list = final_soup.findAll(&#39;h3&#39;, class_="title-text")
    all_name_list = {}
    na="part_name"+str(i)
    all_name_list[na] = part_name
    final_name_list = []###########
    for nlist in name_list:
     nlist = nlist.get_text().replace(view_name, &#39;&#39;).strip()
     final_name_list.append(nlist)
    fin="final_name_list"+str(i)
    all_name_list[fin] = final_name_list
    print(all_name_list)
    i=i+1
    #正文
    try:
     p = re.compile(r&#39;&#39;, re.DOTALL)
     final_soup = final_soup.decode(&#39;utf-8&#39;)
     r = p.search(final_soup)
     final_part_data = final_soup[r.span(0)[0]:]
     part_lists = final_part_data.split(&#39;&#39;)
     for part_list in part_lists:
      final_part_soup = BeautifulSoup(part_list, "html.parser")
      content_lists = final_part_soup.findAll("p", class_="para")
      for content_list in content_lists: # 每个最小段
       try:
        pic_word = content_list.find("p",
                class_="lemma-picture text-pic layout-right").get_text() # 去掉文字中的图片描述
        try:
         pic_word2 = content_list.find("p", class_="description").get_text() # 去掉文字中的图片描述
         content_list = content_list.get_text().replace(pic_word, &#39;&#39;).replace(pic_word2, &#39;&#39;)
        except:
         content_list = content_list.get_text().replace(pic_word, &#39;&#39;)
 
       except:
        try:
         pic_word2 = content_list.find("p", class_="description").get_text() # 去掉文字中的图片描述
         content_list = content_list.get_text().replace(pic_word2, &#39;&#39;)
        except:
         content_list = content_list.get_text()
       r_part = re.compile(r&#39;\[\d.\]|\[\d\]&#39;)
       part_result, number = re.subn(r_part, "", content_list)
       part_result = "".join(part_result.split())
       #print(part_result)
    except:
     final_part_soup = BeautifulSoup(list, "html.parser")
     content_lists = final_part_soup.findAll("p", class_="para")
     for content_list in content_lists:
      try:
       pic_word = content_list.find("p", class_="lemma-picture text-pic layout-right").get_text() # 去掉文字中的图片描述
       try:
        pic_word2 = content_list.find("p", class_="description").get_text() # 去掉文字中的图片描述
        content_list = content_list.get_text().replace(pic_word, &#39;&#39;).replace(pic_word2, &#39;&#39;)
       except:
        content_list = content_list.get_text().replace(pic_word, &#39;&#39;)
 
      except:
       try:
        pic_word2 = content_list.find("p", class_="description").get_text() # 去掉文字中的图片描述
        content_list = content_list.get_text().replace(pic_word2, &#39;&#39;)
       except:
        content_list = content_list.get_text()
      r_part = re.compile(r&#39;\[\d.\]|\[\d\]&#39;)
      part_result, number = re.subn(r_part, "", content_list)
      part_result = "".join(part_result.split())
      #print(part_result)
 
   except:
    print("error")
  return
 
 def output(self,filename):
  json_data = json.dumps(self.view_datas, ensure_ascii=False, indent=2)
  fout = codecs.open(filename+&#39;.json&#39;, &#39;a&#39;, encoding=&#39;utf-16&#39;, )
  fout.write( json_data)
  # print(json_data)
  return
 
 def craw_pic(self,url,filename,html_count):
  soup = BeautifulSoup(html_count, &#39;html.parser&#39;, from_encoding=&#39;utf_8&#39;)
  node_pic=soup.find(&#39;p&#39;,class_=&#39;banner&#39;).find("a", href=re.compile("/photo/poi/....\."))
  if node_pic is None:
   return None
  else:
   part_url_pic=node_pic[&#39;href&#39;]
   full_url_pic=urllib.parse.urljoin(url,part_url_pic)
   #print(full_url_pic)
  try:
   html_pic = urlopen(full_url_pic)
  except HTTPError as e:
   return None
  soup_pic=BeautifulSoup(html_pic.read())
  pic_node=soup_pic.find(&#39;p&#39;,class_="album-list")
  print(pic_node)
  return
 
if __name__ =="__main__" :
 spider=BaikeCraw()
 filename="D:\PyCharm\\view_spider\\view_points_part.txt"
 spider.craw(filename)

总结

用python3根据关键词爬取百度百科的内容到这就基本结束了,希望这篇文章能对大家学习python有所帮助。

更多python3根据关键词爬取百度百科的内容相关文章请关注PHP中文网!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使用Python查找文本文件的ZIPF分布如何使用Python查找文本文件的ZIPF分布Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python处理Zipf定律这一统计概念,并展示Python在处理该定律时读取和排序大型文本文件的效率。 您可能想知道Zipf分布这个术语是什么意思。要理解这个术语,我们首先需要定义Zipf定律。别担心,我会尽量简化说明。 Zipf定律 Zipf定律简单来说就是:在一个大型自然语言语料库中,最频繁出现的词的出现频率大约是第二频繁词的两倍,是第三频繁词的三倍,是第四频繁词的四倍,以此类推。 让我们来看一个例子。如果您查看美国英语的Brown语料库,您会注意到最频繁出现的词是“th

如何在Python中下载文件如何在Python中下载文件Mar 01, 2025 am 10:03 AM

Python 提供多种从互联网下载文件的方法,可以使用 urllib 包或 requests 库通过 HTTP 进行下载。本教程将介绍如何使用这些库通过 Python 从 URL 下载文件。 requests 库 requests 是 Python 中最流行的库之一。它允许发送 HTTP/1.1 请求,无需手动将查询字符串添加到 URL 或对 POST 数据进行表单编码。 requests 库可以执行许多功能,包括: 添加表单数据 添加多部分文件 访问 Python 的响应数据 发出请求 首

我如何使用美丽的汤来解析HTML?我如何使用美丽的汤来解析HTML?Mar 10, 2025 pm 06:54 PM

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

python中的图像过滤python中的图像过滤Mar 03, 2025 am 09:44 AM

处理嘈杂的图像是一个常见的问题,尤其是手机或低分辨率摄像头照片。 本教程使用OpenCV探索Python中的图像过滤技术来解决此问题。 图像过滤:功能强大的工具 图像过滤器

如何使用Python使用PDF文档如何使用Python使用PDF文档Mar 02, 2025 am 09:54 AM

PDF 文件因其跨平台兼容性而广受欢迎,内容和布局在不同操作系统、阅读设备和软件上保持一致。然而,与 Python 处理纯文本文件不同,PDF 文件是二进制文件,结构更复杂,包含字体、颜色和图像等元素。 幸运的是,借助 Python 的外部模块,处理 PDF 文件并非难事。本文将使用 PyPDF2 模块演示如何打开 PDF 文件、打印页面和提取文本。关于 PDF 文件的创建和编辑,请参考我的另一篇教程。 准备工作 核心在于使用外部模块 PyPDF2。首先,使用 pip 安装它: pip 是 P

如何在django应用程序中使用redis缓存如何在django应用程序中使用redis缓存Mar 02, 2025 am 10:10 AM

本教程演示了如何利用Redis缓存以提高Python应用程序的性能,特别是在Django框架内。 我们将介绍REDIS安装,Django配置和性能比较,以突出显示BENE

引入自然语言工具包(NLTK)引入自然语言工具包(NLTK)Mar 01, 2025 am 10:05 AM

自然语言处理(NLP)是人类语言的自动或半自动处理。 NLP与语言学密切相关,并与认知科学,心理学,生理学和数学的研究有联系。在计算机科学

如何使用TensorFlow或Pytorch进行深度学习?如何使用TensorFlow或Pytorch进行深度学习?Mar 10, 2025 pm 06:52 PM

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中