簡體   English   中英

美麗的湯沒有返回預期的結果

[英]Beautiful soup not returning expected result

我正在使用 beautifulsoup 嘗試從網站“https://www.yugiohcardguide.com/archetype/abyss-actor.html”收集信息。 卡片信息設置比較整齊。 下面是我試圖解析的 html 的圖片。

在此處輸入圖像描述

我正在嘗試獲取每行中包含一張卡片信息的所有標簽。

下面是我使用的代碼

def get_card_info_from_link(self, link):
    
    new_link=pre_url+'/'+link #link to the archtype page
    html=requests.get(new_link).content
    soup=bs(html,'lxml')
    info_rows=soup.find('tbody').find_all('tr')
    
    found_cards=[]
    
    # count=0
    
    
    for i in info_rows:
            
            print('='*50)
            print(i)
            print('='*50)
            
            # count+=1

這是我得到的 output 的鏈接。 https://drive.google.com/file/d/1J09nhhrfdje-ktxEG3KLcGwK1cR93ZOo/view?usp=sharing

帶有等號分隔符的前幾個輸出正是我想要的,但在某一時刻,它不再輸出以前的格式,而是一個包含多個標簽的項目,而不是每個標簽都是獨立的。

我無法理解問題所在。 也許我只是忽略了一個我沒有注意到的關鍵細節。

html 損壞或有未閉合的標簽

<tr class="row2" valign="top">
.....
</a> 
<!-- No </td></tr> -->
<tr class="row2" valign="top">

有多種方法可以修復,之后

html = requests.get(new_link).text # instead of .content

使用正則Regex修復它

fixed_html = re.sub(r'</a>\s+<tr valign="top"', '</a></td></tr><tr valign="top"', html)

或使用lxmlhtml5lib

soup = BeautifulSoup(html,'html5lib') # or lxml
fixed_html = soup.prettify()

或使用tidy

fixed_html = tidy.parseString(html, show_body_only=True)

然后解析固定的 html

soup = BeautifulSoup(fixed_html,'lxml')
info_rows = soup.find('tbody').find_all('tr')

可能是這段代碼會幫助你:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.yugiohcardguide.com/archetype/abyss-actor.html')
html = driver.page_source

soup = BeautifulSoup(html, 'html.parser')
result = soup.find('tbody').find_all('tr')
print(result)
driver.close()

暫無
暫無

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

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