使用CSS选择器和Python在表格中对多行单元格进行编程

时间:2016-08-24 20:35:51

标签: python css web-scraping

所以我正在网页抓取一个页面(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]

不幸的是,它只返回每个单元格的名字,而不是两者。我在webscraping工具Kimono上尝试过类似的东西,但我能够抓住这两个东西,但是我想发送一个Python代码,因为Kimono在运行多个网页时会崩溃。

1 个答案:

答案 0 :(得分:2)

问题是某些单元格包含由<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之类的内容。

相关问题