How do I extract table data in pairs using BeautifulSoup?

╄→尐↘猪︶ㄣ 提交于 2020-04-29 11:58:30

问题


My data sample :

<table id = "history">
<tr class = "printCol">
<td class="name">Google</td><td class="date">07/11/2001</td><td class="state">
<span>CA</span>
</td>
</tr>
<tr class = "printCol">
<td class="name">Apple</td><td class="date">27/08/2001</td>
</tr>
<tr class = "printCol">
<td class="name">Microsoft</td><td class="date">01/11/1991</td>
</tr>
</table>

Beautifulsoup code :

table = soup.find("table", id = "history")

rows = table.findAll('tr')
for tr in rows:
    cols = tr.findAll('td')
    for td in cols:
        print td.find(text=True)

Desired Output for MySQL storage (list):

['Google|07/11/2001|CA', 'Apple|27/08/2001', 'Microsoft|01/11/1991']

Output I have (difficult to associate the right date to the right company) :

Google
07/11/2001


Apple
27/08/2001
Microsoft
01/11/1991

I wrote a function to extract elements from each tr but I thought there is a much more efficient way of doing it all in the original for loop. I want to store them in a list as data pairs. Thoughts?


回答1:


List comprehension will make it easier:

table = soup.find("table", id = "history")
rows = table.findAll('tr')
data = [[td.findChildren(text=True) for td in tr.findAll("td")] for tr in rows]
# data now contains:
[[u'Google', u'07/11/2001'],
 [u'Apple', u'27/08/2001'],
 [u'Microsoft', u'01/11/1991']]

# If the data may contain extraneous whitespace you can clean it up
# Additional processing could also be done - but once you hit much more
# complex than this later maintainers, yourself included, will thank you
# for using a series of for loops that call clearly named functions to perform
# the work.
data = [[u"".join(d).strip() for d in l] for l in data]

# If you want to store it joined as name | company
# then simply follow that up with:
data = [u"|".join(d) for d in data]

The list comprehension is basically a reverse for loop with aggregation:

[[td.findNext(text=True) for td in tr.findAll("td")] for tr in rows]

translates into*:

final_list = []
intermediate_list = []

for tr in rows:
    for td in tr.findAll("td")
        intermediate_list.append(td.findNext(text=True))

    final_list.append(intermediate_list)
    intermediate_list = []

data = final_list

* Roughly - we are leaving out the awesomeness involving generators not building intermediate lists, since I can't add generators right now without cluttering the example.




回答2:


Here is small variation of Sean answer if you need exactly what you wrote in question,

table = soup.find("table", id = "history")

rows = table.findAll('tr')

data = ['|'.join([td.findNext(text=True) for td in tr.findAll("td")]) for tr in rows]
print data


来源:https://stackoverflow.com/questions/8139797/how-do-i-extract-table-data-in-pairs-using-beautifulsoup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!