Skip to main content
 首页 » 编程设计

python之使用 CSS 选择器和 Python 抓取表格中的多行单元格

2024年10月17日6lvdongjie

所以我正在网络抓取一个页面(http://canoeracing.org.uk/marathon/results/burton2016.htm),其中表格中有多行单元格:

我正在使用以下代码来抓取每一列(下面的代码恰好抓取了名称):

import lxml.html 
from lxml.cssselect import CSSSelector 
 
# get some html 
import requests 
 
r = requests.get('http://canoeracing.org.uk/marathon/results/burton2016.htm') 
# build the DOM Tree 
tree = lxml.html.fromstring(r.text) 
# construct a CSS Selector 
sel1 = CSSSelector('body > table > tr > td:nth-child(2)') 
# Apply the selector to the DOM tree. 
results1 = sel1(tree) 
# get the text out of all the results 
data1 = [result.text for result in results1] 

不幸的是,它只返回每个单元格的名字,而不是两个。我在网络抓取工具 Kimono 上尝试过类似的事情,我能够抓取两者,但是我想发送一个 Python 代码,因为 Kimono 在运行多个网页时会掉下来。

请您参考如下方法:

问题是某些单元格包含多个由 <br> 分隔的文本节点.在这种情况下,找到所有文本节点并加入它们:

data1 = [", ".join(result.xpath("text()")) for result in rows]  

对于屏幕截图中提供的行,您将得到:

OSCAR HUISSOON, FREJA WEBBER 
ELLIE LAWLEY, RHYS TIPPINGS 
ALLISON MILES, ALEX MILES 
NICOLA RUDGE, DEBORAH CRUMP 

你也可以使用 .text_content()方法,但你会丢失文本节点之间的分隔符,得到类似 OSCAR HUISSOONFREJA WEBBER 的东西在结果中。