从大型表格中,我想读取第5,10,15,20行...使用BeautifulSoup。我该怎么做呢? findNextSibling是一个增长计数器吗?使用BeautifulSoup获取第n个元素
14
A
回答
31
你也可以使用findAll
获取列表中的所有行之后,仅仅用切片语法访问您需要的元素:
rows = soup.findAll('tr')[4::5]
1
作为一个通用的解决方案,你可以转换表到嵌套列表和迭代...
import BeautifulSoup
def listify(table):
"""Convert an html table to a nested list"""
result = []
rows = table.findAll('tr')
for row in rows:
result.append([])
cols = row.findAll('td')
for col in cols:
strings = [_string.encode('utf8') for _string in col.findAll(text=True)]
text = ''.join(strings)
result[-1].append(text)
return result
if __name__=="__main__":
"""Build a small table with one column and ten rows, then parse into a list"""
htstring = """<table> <tr> <td>foo1</td> </tr> <tr> <td>foo2</td> </tr> <tr> <td>foo3</td> </tr> <tr> <td>foo4</td> </tr> <tr> <td>foo5</td> </tr> <tr> <td>foo6</td> </tr> <tr> <td>foo7</td> </tr> <tr> <td>foo8</td> </tr> <tr> <td>foo9</td> </tr> <tr> <td>foo10</td> </tr></table>"""
soup = BeautifulSoup.BeautifulSoup(htstring)
for idx, ii in enumerate(listify(soup)):
if ((idx+1)%5>0):
continue
print ii
运行的是......
[[email protected] ~]$ python testme.py
['foo5']
['foo10']
[[email protected] ~]$
1
另一种选择,如果你喜欢原始的HTML ...
"""Build a small table with one column and ten rows, then parse it into a list"""
htstring = """<table> <tr> <td>foo1</td> </tr> <tr> <td>foo2</td> </tr> <tr> <td>foo3</td> </tr> <tr> <td>foo4</td> </tr> <tr> <td>foo5</td> </tr> <tr> <td>foo6</td> </tr> <tr> <td>foo7</td> </tr> <tr> <td>foo8</td> </tr> <tr> <td>foo9</td> </tr> <tr> <td>foo10</td> </tr></table>"""
result = [html_tr for idx, html_tr in enumerate(soup.findAll('tr')) \
if (idx+1)%5==0]
print result
运行的是......
[[email protected] ~]$ python testme.py
[<tr> <td>foo5</td> </tr>, <tr> <td>foo10</td> </tr>]
[[email protected] ~]$
1
这可以用select
轻松完成美丽的汤,如果你知道行号来选择。 (注:这是在BS4)
row = 5
while true
element = soup.select('tr:nth-of-type('+ row +')')
if len(element) > 0:
# element is your desired row element, do what you want with it
row += 5
else:
break
相关问题
- 1. Python BeautifulSoup刮第n种元素
- 2. 使用jquery获取元素的第n个子值
- 3. 使用XmlArrow从页面获取第n个元素?
- 4. 使用Xpath和Jquery获取第N个元素
- 5. 获取元素相对于第n个父元素的位置
- 6. 获得集合的第n个元素
- 7. 通过base px * n第n个元素缩进每个第n个元素
- 8. 获取第n个素数的Javascript
- 9. 从Observable中获取每个第N个元素
- 10. 获取对象中某个键的第n个元素
- 11. Zen第n个元素
- 12. 使用BeautifulSoup获取下一个UL元素
- 13. 使用公式获得第n个输入元素的值
- 14. 使用lxml/XPath获得第n个元素失败
- 15. 获取特定元素(N,)
- 16. 获取<table>元素的第n个innerHTML的动态
- 17. 获取元素的第n个孩子数量纯JavaScript
- 18. 获取查询中第一个N元素的平均值LARAVEL
- 19. 如何获取第n个计数的NSArray元素?
- 20. Android - Java - 获取JSONObject中的第n个元素
- 21. 获取集合的第n个元素在Cypher支架
- 22. 从VBA字符串数组中获取第n个元素
- 23. Oracle SQL获取第n个元素正则表达式
- 24. 获取第n个元素(如果它不包含类)
- 25. 从Haskell中的二叉树中获取第N个元素
- 26. 获取Rafael.js的第n个元素的x坐标文本元素的集合
- 27. 获取数组的前N个元素?
- 28. 获取std :: list的前N个元素?
- 29. MySql:获取至少N个元素
- 30. 在等待中使用Selenium中的Xpath获取第n个元素的出现
这很干净。注意find all方法返回一个数组,所以这很好。 – JasTonAChair 2015-11-06 02:51:00