Perché questa estrazione funziona bene nell'esempio, ma non sull'URL reale?

Aug 22 2020

Sto cercando di estrarre il contenuto di hrefin classe a, che è dentro <td class="DataZone">. Funziona nell'esempio seguente

from bs4 import BeautifulSoup

text = '''
<td class="DataZone"><div id="Content_CA_DI_0_DataZone">
<div style="font:bold 8pt 'Courier New';letter-spacing:-1px">
<a href="Browse-A">A</a> <a href="Browse-B">B</a> <a href="Browse-C">C</a> <a href="Browse-D">D</a> 
</div>
</div></td>
'''

soup = BeautifulSoup(text, 'html.parser')

[tag.attrs['href'] for tag in soup.select('td.DataZone a')]

e il risultato è ['Browse-A', 'Browse-B', 'Browse-C', 'Browse-D']. Quando lo applico su un URL reale , purtroppo non funziona

import requests
session = requests.Session()
from bs4 import BeautifulSoup

url = 'https://www.thefreedictionary.com'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
r = session.get(url, headers = headers) 
soup = BeautifulSoup(r.content, 'html.parser')

[tag.attrs['href'] for tag in soup.select('td.DataZone a')]

Restituisce un errore

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-12-0a06dde2d97b> in <module>
      4 soup = BeautifulSoup(r.content, 'html.parser')
      5 
----> 6 [tag.attrs['href'] for tag in soup.select('td.DataZone a')]

<ipython-input-12-0a06dde2d97b> in <listcomp>(.0)
      4 soup = BeautifulSoup(r.content, 'html.parser')
      5 
----> 6 [tag.attrs['href'] for tag in soup.select('td.DataZone a')]

KeyError: 'href'

Chiaramente, la fonte dell'URL è simile all'esempio

Potresti spiegare perché si verifica questo errore?


Aggiornamento: è strano per me che [x['href'] for x in soup.select('td.DataZone a[href^=Browse]')]funzioni bene, ma non [x['href'] for x in soup.select('td.DataZone a')]. Si prega di approfondire anche la questione.

Risposte

2 AndrejKesely Aug 22 2020 at 17:46

Stai ricevendo l'errore, perché ci sono molti td.Datazonetag e all'interno di uno dei tag c'è <a>Google+</a>- che è senza href.

Puoi selezionare da td.DataZone a[href]per selezionare solo i <a>tag con hrefattributo:

print( [tag.attrs['href'] for tag in soup.select('td.DataZone a[href]')] )
2 Ava Aug 22 2020 at 17:12

Sembra che non tutti i <a>tag abbiano hrefattributi. Prova questo invece.

l = [tag.attrs['href'] for tag in soup.select('td.DataZone a') if 'href' in tag.attrs]
print(*l, sep = '\n')

Puoi anche farlo.

l = [tag.attrs['href'] for tag in soup.select('td.DataZone a[attr="href"]')]
print(*l, sep = '\n')
2 αԋɱҽԃαмєяιcαη Aug 22 2020 at 17:10

Il punto qui che stai usando un CSSselettore sbagliato .

import requests
from bs4 import BeautifulSoup


def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    target = [x['href'] for x in soup.select("a[href^=Browse]")]
    print(target)


main("https://www.thefreedictionary.com/")

O:

target = [x for x in soup.select("td.DataZone a[href^=Browse]")]

Produzione:

['Browse-A', 'Browse-B', 'Browse-C', 'Browse-D', 'Browse-E', 'Browse-F', 'Browse-G', 'Browse-H', 'Browse-I', 'Browse-J', 'Browse-K', 'Browse-L', 'Browse-M', 'Browse-N', 'Browse-O', 'Browse-P', 'Browse-Q', 'Browse-R', 'Browse-S', 'Browse-T', 'Browse-U', 'Browse-V', 'Browse-W', 'Browse-X', 'Browse-Y', 'Browse-Z']

Aggiornamento in base ai requisiti dell'utente nel commento:

import requests
from bs4 import BeautifulSoup


def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    for item in soup.select("td.DataZone"):
        for x in item.findAll(href=True):
            print(x['href'])


main("https://www.thefreedictionary.com/")