Answer a question

I am trying to scrape a table from Wikipedia

<tr>
  <td>1</td>
  <td><span class="nowrap"><span class="datasortkey" data-sort-value="Etats unis"><span class="flagicon"><a class="image" href="/wiki/Fichier:Flag_of_the_United_States.svg" title="Drapeau des États-Unis"><img alt="Drapeau des États-Unis" class="noviewer thumbborder" data-file-height="650" data-file-width="1235" height="11" src="//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_the_United_States.svg/20px-Flag_of_the_United_States.svg.png" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_the_United_States.svg/30px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_the_United_States.svg/40px-Flag_of_the_United_States.svg.png 2x" width="20" /></a> </span><a href="/wiki/%C3%89tats-Unis" title="États-Unis">États-Unis</a></span></span></td>
  <td>19 390,60 </td>
</tr>

as you have noticed there are 3 columns, and here is the code i'm using

A = []
B = []
C = []

for row in DataFondMonetaireInt.findAll("tr"):
    cells = row.findAll("td")
    if len(cells) == 3:
        A.append(cells[0].find(text=True))
        B.append(cells[1].find(text=True))
        C.append(cells[2].find(text=True))

It works well for A and C but not for B, i can't get the country name (in the example : Etats Unis)

why doesn't it work ?

thank you in advance,

Answers

use .text instead of .find(text=True)

DataFondMonetaireInt = BeautifulSoup(html_text, "html.parser")

A = []
B = []
C = []

for row in DataFondMonetaireInt.findAll("tr"):
    cells = row.findAll("td")
    if len(cells) == 3:
        A.append(cells[0].text)
        B.append(cells[1].text.strip())
        C.append(cells[2].text)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐