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对文件的操作读写追加等演示

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容