教你用python3根據(jù)關(guān)鍵詞爬取百度百科的內(nèi)容
前言
關(guān)于python版本,我一開始看很多資料說python2比較好,因?yàn)楹芏鄮爝€不支持3,但是使用到現(xiàn)在為止覺得還是pythin3比較好用,因?yàn)榫幋a什么的問題,覺得2還是沒有3方便。而且在網(wǎng)上找到的2中的一些資料稍微改一下也還是可以用。
好了,開始說爬百度百科的事。
這里設(shè)定的需求是爬取北京地區(qū)n個(gè)景點(diǎn)的全部信息,n個(gè)景點(diǎn)的名稱是在文件中給出的。沒有用到api,只是單純的爬網(wǎng)頁信息。
1、根據(jù)關(guān)鍵字獲取url
由于只需要爬取信息,而且不涉及交互,可以使用簡單的方法而不需要模擬瀏覽器。
可以直接
<strong>http://baike.baidu.com/search/word?word="guanjianci"</strong>
<strong>for </strong>l <strong>in </strong>view_names: <strong>'''http://baike.baidu.com/search/word?word=''' </strong><em># 得到url的方法 </em><em> </em>name=urllib.parse.quote(l) name.encode(<strong>'utf-8'</strong>) url=<strong>'http://baike.baidu.com/search/word?word='</strong>+name
這里要注意關(guān)鍵詞是中午所以要注意編碼問題,由于url中不能出現(xiàn)空格,所以需要用quote函數(shù)處理一下。
關(guān)于quote():
在 Python2.x 中的用法是:urllib.quote(text) 。Python3.x 中是urllib.parse.quote(text) 。按照標(biāo)準(zhǔn),URL只允許一部分ASCII 字符(數(shù)字字母和部分符號(hào)),其他的字符(如漢字)是不符合URL標(biāo)準(zhǔn)的。所以URL中使用其他字符就需要進(jìn)行URL編碼。URL中傳參數(shù)的部分(query String),格式是:name1=value1&name2=value2&name3=value3。假如你的name或者value值中的『&』或者『=』等符號(hào),就當(dāng)然會(huì)有問題。所以URL中的參數(shù)字符串也需要把『&=』等符號(hào)進(jìn)行編碼。URL編碼的方式是把需要編碼的字符轉(zhuǎn)化為%xx的形式。通常URL編碼是基于UTF-8的(當(dāng)然這和瀏覽器平臺(tái)有關(guān))
例子:
比如『我,unicode 為 0x6211,UTF-8編碼為0xE60x880x91,URL編碼就是 %E6%88%91。
Python的urllib庫中提供了quote和quote_plus兩種方法。這兩種方法的編碼范圍不同。不過不用深究,這里用quote就夠了。
2、下載url
用urllib庫輕松實(shí)現(xiàn),見下面的代碼中def download(self,url)
3、利用Beautifulsoup獲取html
4、數(shù)據(jù)分析
百科中的內(nèi)容是并列的段,所以在爬的時(shí)候不能自然的按段邏輯存儲(chǔ)(因?yàn)槿际遣⒘械模?。所以必須用正則的方法。
基本的想法就是把整個(gè)html文件看做是str,然后用正則的方法截取想要的內(nèi)容,在重新把這段內(nèi)容轉(zhuǎn)換成beautifulsoup對(duì)象,然后在進(jìn)一步處理。
可能要花些時(shí)間看一下正則。
代碼中還有很多細(xì)節(jié),忘了再查吧只能,下次絕對(duì)應(yīng)該邊做編寫文檔,或者做完馬上寫。。。
貼代碼!
# coding:utf-8
'''
function:爬取百度百科所有北京景點(diǎn),
author:yi
'''
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")
'''file=self.view_datas["view_name"]
self.craw_pic(urll,file,html_count)
print(file)'''
def getUrls (self, filename):
new_urls = set()
file_object = codecs.open(filename, encoding='utf-16', )
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 '?' in l:
view_names.remove(l)
for l in view_names:
'''http://baike.baidu.com/search/word?word=''' # 得到url的方法
name=urllib.parse.quote(l)
name.encode('utf-8')
url='http://baike.baidu.com/search/word?word='+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, 'html.parser', from_encoding='utf_8')
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): ##得到數(shù)據(jù)
if soup.find('div',class_="main-content").find('h1') is not None:
self.view_datas["view_name"]=soup.find('div',class_="main-content").find('h1').get_text()#景點(diǎn)名
print(self.view_datas["view_name"])
else:
self.view_datas["view_name"] = soup.find("div", class_="feature_poster").find("h1").get_text()
self.view_datas["view_message"] = soup.find('div', class_="lemma-summary").get_text()#簡介
self.view_datas["basic_message"]=soup.find('div', 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('div', 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
#########################百科內(nèi)容
view_name=self.view_datas["view_name"]
html = urllib.request.urlopen(url)
soup2 = BeautifulSoup(html.read(), 'html.parser').decode('utf-8')
p = re.compile(r'', re.DOTALL) # 尾
r = p.search(content_data_node)
content_data = content_data_node[0:r.span(0)[0]]
lists = content_data.split('')
i = 1
for list in lists:#每一大塊
final_soup = BeautifulSoup(list, "html.parser")
name_list = None
try:
part_name = final_soup.find('h2', class_="title-text").get_text().replace(view_name, '').strip()
part_data = final_soup.get_text().replace(view_name, '').replace(part_name, '').replace('編輯', '') # 歷史沿革
name_list = final_soup.findAll('h3', 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, '').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'', re.DOTALL)
final_soup = final_soup.decode('utf-8')
r = p.search(final_soup)
final_part_data = final_soup[r.span(0)[0]:]
part_lists = final_part_data.split('')
for part_list in part_lists:
final_part_soup = BeautifulSoup(part_list, "html.parser")
content_lists = final_part_soup.findAll("div", class_="para")
for content_list in content_lists: # 每個(gè)最小段
try:
pic_word = content_list.find("div",
class_="lemma-picture text-pic layout-right").get_text() # 去掉文字中的圖片描述
try:
pic_word2 = content_list.find("div", class_="description").get_text() # 去掉文字中的圖片描述
content_list = content_list.get_text().replace(pic_word, '').replace(pic_word2, '')
except:
content_list = content_list.get_text().replace(pic_word, '')
except:
try:
pic_word2 = content_list.find("div", class_="description").get_text() # 去掉文字中的圖片描述
content_list = content_list.get_text().replace(pic_word2, '')
except:
content_list = content_list.get_text()
r_part = re.compile(r'\[\d.\]|\[\d\]')
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("div", class_="para")
for content_list in content_lists:
try:
pic_word = content_list.find("div", class_="lemma-picture text-pic layout-right").get_text() # 去掉文字中的圖片描述
try:
pic_word2 = content_list.find("div", class_="description").get_text() # 去掉文字中的圖片描述
content_list = content_list.get_text().replace(pic_word, '').replace(pic_word2, '')
except:
content_list = content_list.get_text().replace(pic_word, '')
except:
try:
pic_word2 = content_list.find("div", class_="description").get_text() # 去掉文字中的圖片描述
content_list = content_list.get_text().replace(pic_word2, '')
except:
content_list = content_list.get_text()
r_part = re.compile(r'\[\d.\]|\[\d\]')
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+'.json', 'a', encoding='utf-16', )
fout.write( json_data)
# print(json_data)
return
def craw_pic(self,url,filename,html_count):
soup = BeautifulSoup(html_count, 'html.parser', from_encoding='utf_8')
node_pic=soup.find('div',class_='banner').find("a", href=re.compile("/photo/poi/....\."))
if node_pic is None:
return None
else:
part_url_pic=node_pic['href']
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('div',class_="album-list")
print(pic_node)
return
if __name__ =="__main__" :
spider=BaikeCraw()
filename="D:\PyCharm\\view_spider\\view_points_part.txt"
spider.craw(filename)
總結(jié)
用python3根據(jù)關(guān)鍵詞爬取百度百科的內(nèi)容到這就基本結(jié)束了,希望這篇文章能對(duì)大家學(xué)習(xí)python有所幫助。
相關(guān)文章
Python使用pydub模塊轉(zhuǎn)換音頻格式以及對(duì)音頻進(jìn)行剪輯
這篇文章主要給大家介紹了關(guān)于Python使用pydub模塊轉(zhuǎn)換音頻格式以及對(duì)音頻進(jìn)行剪輯的相關(guān)資料pydub是python的高級(jí)一個(gè)音頻處理庫,可以讓你以一種不那么蠢的方法處理音頻。需要的朋友可以參考下2021-06-06
python?pandas創(chuàng)建多層索引MultiIndex的6種方式
這篇文章主要為大家介紹了python?pandas創(chuàng)建多層索引MultiIndex的6種方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Pytorch 中net.train 和 net.eval的使用說明
這篇文章主要介紹了Pytorch 中net.train 和 net.eval的使用說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
tensorflow實(shí)現(xiàn)對(duì)張量數(shù)據(jù)的切片操作方式
今天小編就為大家分享一篇tensorflow實(shí)現(xiàn)對(duì)張量數(shù)據(jù)的切片操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python PyQt5干貨滿滿小項(xiàng)目輕松實(shí)現(xiàn)高效摳圖去背景
PyQt5以一套Python模塊的形式來實(shí)現(xiàn)功能。它包含了超過620個(gè)類,600個(gè)方法和函數(shù)。本篇文章手把手帶你用PyQt5輕松實(shí)現(xiàn)圖片扣除背景,大家可以在過程中查缺補(bǔ)漏,提升水平2021-11-11
Python sklearn對(duì)文本數(shù)據(jù)進(jìn)行特征化提取
這篇文章主要介紹了Python sklearn對(duì)文本數(shù)據(jù)進(jìn)行特征化提取,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-04-04
numpy使用技巧之?dāng)?shù)組過濾實(shí)例代碼
這篇文章主要介紹了numpy使用技巧之?dāng)?shù)組過濾實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Python使用ConfigParser模塊操作配置文件的方法
這篇文章主要介紹了Python使用ConfigParser模塊操作配置文件的方法,結(jié)合實(shí)例形式分析了Python基于ConfigParser模塊針對(duì)配置文件的創(chuàng)建、讀取、寫入、判斷等相關(guān)操作技巧,需要的朋友可以參考下2018-06-06

