簡體   English   中英

美麗的湯/正則表達式:從NavigableString中提取一部分文本

[英]Beautiful Soup / Regular Expressions: Extract a portion of text from NavigableString

我是學習python的新手,所以這可能非常明顯,但是我從BeautifulSoup中提取了一個NavigableString,我需要在字符串中查找數據。 但是,它並不像我在網上看到的一些例子那么容易。

我的最終目標是創建一個類似於下面的字典:

dict = {'Fandom':'Undertale (Video Game)', 'Works':15341}

以下是字符串的兩個示例:

<li>
<a class="tag" href="/tags/Undertale%20(Video%20Game)/works">Undertale (Video Game)</a>
          (15341)
      </li>

<a class="tag" href="/tags/Sherlock%20Holmes%20*a*%20Related%20Fandoms/works">Sherlock Holmes &amp; Related Fandoms</a>
          (101015)
      </li>

我已經成功地從字符串中提取了粉絲,但現在我需要括號中的工作計數。 我如何使用Beautiful Soup和/或Regular Expressions來做到這一點?

我還需要進行錯誤處理,因為雖然總是會顯示一個粉絲,但它旁邊可能沒有工作計數。

<li>
<a class="tag" href="/tags/Composer%20-%20Fandom/works">Composer - Fandom</a>
</li>

這是相關的代碼片段:

        for each_f in cate:
            #print(each_f)
            result = each_f.find('a')
            if result !=-1:
                #here is where I grab the Fandom vals
                fandom_name = result.contents
                #print(result.contents)

注意:我知道我錯過了附加到字典的代碼,我還沒有做到那么遠。 我只是想把值打印到屏幕上。

您可以使用stripped_strings並解壓縮值以獲取文本塊。 您可以將結果存儲在dict以便以后使用它們。

例:

from bs4 import BeautifulSoup
import requests


example = """<li>
<a class="tag" href="/tags/Undertale%20(Video%20Game)/works">Undertale (Video Game)</a>
      (15341)
  </li>

<li><a class="tag"     href="/tags/Sherlock%20Holmes%20*a*%20Related%20Fandoms/works">Sherlock Holmes &amp; Related Fandoms</a>
      (101015)
  </li>
  <li>
<a class="tag" href="/tags/Composer%20-%20Fandom/works">Composer - Fandom</a>
</li>"""

soup = BeautifulSoup(example, "html.parser")
Fandom = {"Fandom" : []}

for li in soup.find_all("li"):
    try:
        fandom, count = li.stripped_strings
        Fandom["Fandom"].append({fandom.strip() : count[1:-1]})
    except:
        fandom = li.text.strip()
        Fandom["Fandom"].append({fandom.strip() : 0})

print (Fandom)

這輸出:

{'Fandom':[{'Undertale(電子游戲)':'15341'},{'Sherlock Holmes及相關的同人圈':'101015'},{'作曲家 - 粉絲':0}]}

try-catch將捕獲任何不包含兩個值的解包:你的粉絲標題和單詞計數。

使用dict.fromkeys(('Fandom', 'Works'))得到:

In [17]: dict.fromkeys(('Fandom', 'Works'))
Out[17]: {'Fandom': None, 'Works': None}

使用zip將鍵與li標簽中的字符串組合在一起,這只會結​​合最短的:

zip(('Fandom', 'Works'),li.stripped_strings)

[('Fandom', 'Undertale (Video Game)'), ('Works', '(15341)')]
[('Fandom', 'Sherlock Holmes & Related Fandoms'), ('Works', '(101015)')]
[('Fandom', 'Composer - Fandom')]

然后我們用這些數據更新dict

In [20]: for li in soup.find_all('li'):
    ...:     d = dict.fromkeys(('Fandom', 'Works'))
    ...:     out = zip(('Fandom', 'Works'),li.stripped_strings)
    ...:     d.update(out)
    ...:     print(d)

出:

{'Works': '(15341)', 'Fandom': 'Undertale (Video Game)'}
{'Works': '(101015)', 'Fandom': 'Sherlock Holmes & Related Fandoms'}
{'Works': None, 'Fandom': 'Composer - Fandom'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM