python爬蟲練手,爬取名言团驱,實現英語詞典

要爬取的網站 http://quotes.toscrape.com/

image.png

爬取名言摸吠,作者,標簽嚎花。*

她們的Html為寸痢,通過beautiful庫的html.parser解析,通過id,class選擇器紊选,提取我們需要的東西啼止。

<span class="text" itemprop="text">“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”</span>

<span class="text" itemprop="text">“It is our choices, Harry, that show what we truly are, far more than our abilities.”</span>



<div class="tags">
            Tags:
            <meta class="keywords" itemprop="keywords" content="change,deep-thoughts,thinking,world"> 
            
            <a class="tag" href="/tag/change/page/1/">change</a>
            
            <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a>
            
            <a class="tag" href="/tag/thinking/page/1/">thinking</a>
            
            <a class="tag" href="/tag/world/page/1/">world</a>
            
        </div>


<div class="tags">
            Tags:
            <meta class="keywords" itemprop="keywords" content="abilities,choices"> 
            
            <a class="tag" href="/tag/abilities/page/1/">abilities</a>
            
            <a class="tag" href="/tag/choices/page/1/">choices</a>
            
        </div>

<small class="author" itemprop="author">J.K. Rowling</small>

相關的code如下

import requests
import os
from bs4 import BeautifulSoup

def get_html(url):
    try:
        header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.90 Safari/537.36 2345Explorer/9.3.2.17331', }
        ht=requests.get(url,headers=header,verify=True)
        ht.raise_for_status
        ht.encoding=ht.apparent_encoding
        return ht
    except Exception as e:
        print("error:",e)
        
       
    
        
def writeHtml(url):
    text=get_html(url).content
    path="C:\\Users\\Administrator\\Desktop\\python\\baidu.html"
    with open(path,"wb") as f:
        f.write(text)
print("success")



def getInfor(url):
    finalSay=[]
    html=get_html(url).text
    soup=BeautifulSoup(html,"html.parser")
    print(" the saying is:")
    say_list=soup.select("span.text")
    print("-------名言--------------")
    print("the length=",len(say_list))
   # print(say_list)
    for elem in say_list:
        te=elem.text
        finalSay.append(te);
    print(finalSay)
    print("-------標簽--------------")
    finalTag=[]
    tag_list=soup.select("div.tags")
    print("the length of tag=",len(tag_list))
    #print(tag_list)
    for tag in tag_list:
        a_tag=tag.select("a.tag")
        #print(a_tag)
        
       # for elem in a_tag:
       #    print(elem.text)
        tag_list=[elem.text for elem in a_tag]
        #print(tag_list)
        finalTag.append(tag_list)
    print(finalTag)
    print("-------作者--------------")
    finalAuthor=[]
    author_list=soup.select("small.author")
    print("the length of authoer=",len(author_list))
    for elem in author_list:
        finalAuthor.append(elem.text)
    print(finalAuthor)
    for i in range(len(author_list)):
        print("the saying:",finalSay[i],"\t","the author:",finalAuthor[i],"\t","the tag:",finalTag[i])
    
    

結果如下

the saying: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”          the author: Albert Einstein     the tag: ['change', 'deep-thoughts', 'thinking', 'world']
the saying: “It is our choices, Harry, that show what we truly are, far more than our abilities.”        the author: J.K. Rowling        the tag: ['abilities', 'choices']
the saying: “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”          the author: Albert Einstein     the tag: ['inspirational', 'life', 'live', 'miracle', 'miracles']
the saying: “The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”     the author: Jane Austen         the tag: ['aliteracy', 'books', 'classic', 'humor']
the saying: “Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”      the author: Marilyn Monroe      the tag: ['be-yourself', 'inspirational']
the saying: “Try not to become a man of success. Rather become a man of value.”          the author: Albert Einstein     the tag: ['adulthood', 'success', 'value']
the saying: “It is better to be hated for what you are than to be loved for what you are not.”   the author: André Gide          the tag: ['life', 'love']
the saying: “I have not failed. I've just found 10,000 ways that won't work.”    the author: Thomas A. Edison    the tag: ['edison', 'failure', 'inspirational', 'paraphrased']
the saying: “A woman is like a tea bag; you never know how strong it is until it's in hot water.”        the author: Eleanor Roosevelt   the tag: ['misattributed-eleanor-roosevelt']
the saying: “A day without sunshine is like, you know, night.”   the author: Steve Martin        the tag: ['humor', 'obvious', 'simile']

借助bing的翻譯,實現英語翻譯中文

完整 https://cn.bing.com/dict/search?q=snow

其翻譯的信息主要在


<span class="pos">n.</span>
<span class="pos">v.</span>
<span class="pos">adj.</span>
<span class="pos web">網絡</span>

<span class="def"><span>書兵罢;書籍献烦;著作;部</span></span>
<span class="def"><span>書籍的卖词;書本上的巩那;賬面上的</span></span>

對應的正則表達式為

 re0=r'<span class="(pos|pos web)">(.*?)</span>'
 re1=r'<span class="def"><span>(.*?)</span></span>'

相關code
主要是正則表達式的使用,已經寫文件操作此蜈。

def getDictionary():
    word=input("親輸入要翻譯的詞語:")
    url="https://cn.bing.com/dict/search?q="
    hurl=url+word
    trant=[]
    html=get_html(hurl).text
    re0=r'<span class="(pos|pos web)">(.*?)</span>'
    flag_list=[]
    nav_list=re.findall(re0,html)
    #print(hurl)
    #print(html)
    if len(nav_list)==0 and len(nav_list[0])<1:
        return 
    for elem in nav_list:
        flag_list.append(elem[1])  
    print(flag_list)
    re1=r'<span class="def"><span>(.*?)</span></span>'
    tran_list=re.findall(re1,html)
    #print(tran_list)
    for i in range(len(nav_list)):
        tra="\t".join([flag_list[i],tran_list[i]])
        print(tra)
        trant.append(tra)
        #trant.append("\n")
    return trant
        
         
        
def writeTet(t):
    path="E:\\infor.txt"
    with open(path,"a+") as f:
        for txt in t:
             f.write(txt)
             f.write("\n")
    print("success")

結果為


親輸入要翻譯的詞語:Python
['n.', '網絡']
n.      蟒即横;蚺蛇
網絡      蟒蛇;巨蟒裆赵;派森
success

image.png

參考文章
beautifulsoup之CSS選擇器
Beautiful Soup Documentation
Python 文件I/O
python對文件的操作讀寫追加等演示

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末东囚,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子战授,更是在濱河造成了極大的恐慌舔庶,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件陈醒,死亡現場離奇詭異惕橙,居然都是意外死亡,警方通過查閱死者的電腦和手機钉跷,發(fā)現死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門弥鹦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事彬坏‰伲” “怎么了?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵栓始,是天一觀的道長务冕。 經常有香客問我,道長幻赚,這世上最難降的妖魔是什么禀忆? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮落恼,結果婚禮上箩退,老公的妹妹穿的比我還像新娘。我一直安慰自己佳谦,他們只是感情好戴涝,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著钻蔑,像睡著了一般啥刻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上咪笑,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天可帽,我揣著相機與錄音,去河邊找鬼蒲肋。 笑死蘑拯,一個胖子當著我的面吹牛钝满,可吹牛的內容都是我干的兜粘。 我是一名探鬼主播,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼弯蚜,長吁一口氣:“原來是場噩夢啊……” “哼孔轴!你這毒婦竟也來了?” 一聲冷哼從身側響起碎捺,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤路鹰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后收厨,有當地人在樹林里發(fā)現了一具尸體晋柱,經...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年诵叁,在試婚紗的時候發(fā)現自己被綠了雁竞。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖碑诉,靈堂內的尸體忽然破棺而出彪腔,到底是詐尸還是另有隱情,我是刑警寧澤进栽,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布德挣,位于F島的核電站,受9級特大地震影響快毛,放射性物質發(fā)生泄漏格嗅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一祸泪、第九天 我趴在偏房一處隱蔽的房頂上張望吗浩。 院中可真熱鬧,春花似錦没隘、人聲如沸懂扼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽阀湿。三九已至,卻和暖如春瑰妄,著一層夾襖步出監(jiān)牢的瞬間陷嘴,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工间坐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留灾挨,地道東北人。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓竹宋,卻偏偏與公主長得像劳澄,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蜈七,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內容