使用CSS选择器和Python在表中创建多行单元格

2024-05-16 23:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我在web上创建一个页面(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上也尝试过类似的东西,我都能抓取到,但是我想在Kimono在运行多个网页时失败时发送一个Python代码。在


Tags: the代码textorgimporttreehttpget
1条回答
网友
1楼 · 发布于 2024-05-16 23:45:42

问题是有些单元格包含多个由<br>分隔的文本节点。在这种情况下,查找所有文本节点并将它们连接起来:

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

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

^{pr2}$

您也可以使用.text_content()方法,但是您将丢失文本节点之间的分隔符,从而在结果中得到类似于OSCAR HUISSOONFREJA WEBBER的内容。在

相关问题 更多 >